gpt4 book ai didi

junit - 如何使用 Koin 注入(inject) @BeforeClass 静态方法?

转载 作者:行者123 更新时间:2023-12-01 11:14:25 29 4
gpt4 key购买 nike

我有一个集成测试,需要在运行任何后续测试之前调用 REST 服务以获取访问 token 一次。在将 Koin 添加到我的项目之前,我在一个带有 @BeforeClass 注释的静态方法中完成了这项工作,如下所示:

class PersonRepositoryIntegrationTest {

companion object {
private var _clientToken: String? = null

@BeforeClass
@JvmStatic
fun setup() {
_clientToken = AuthRepository().getClientToken()!!.accessToken
}
}

@Test
fun testCreatePerson() {
PersonRepository().createPerson(_clientToken)
}

AuthRepository 和 PersonRepository 有额外的依赖关系,到目前为止,这些依赖关系是在它们的构造函数中实例化的。现在,我想使用 Koin 通过注入(inject)存储库来解决这些依赖关系:

class PersonRepositoryIntegrationTest : KoinTest {

companion object {
private val _authRepository by inject<IAuthRepository>()
private val _personRepository by inject<IPersonRepository>()
private var _clientToken: String? = null

@BeforeClass
@JvmStatic
fun beforeClass() {
startKoin(listOf(AppModule.appModule))
_clientToken = _authRepository.getClientToken()!!.accessToken
}
}

当我尝试在伴生对象中使用 inject 时,编译器会报错:

Unresolved reference.
None of the following candidates is applicable because of receiver type mismatch.

* public inline fun <reified T : Any> KoinComponent.inject(name: String = ..., scope: Scope? = ..., noinline parameters: ParameterDefinition = ...): Lazy<IAuthRepository> defined in org.koin.standalone

还有其他方法可以使用 Koin 在像这样的 @BeforeClass 静态方法中注入(inject)我的类吗?

最佳答案

根据 kotlin documentation , 伴生对象在技术上是真实的对象。

even though the members of companion objects look like static members in other languages, at runtime those are still instance members of real objects, and can, for example, implement interfaces:

如果一个类想要注入(inject)依赖并且它不是 koin 支持的类之一(Activity、Fragment、ViewModel、KoinTest 等),那么该类应该实现 KoinComponent 接口(interface)。

因此,请考虑将伴随对象定义更改为以下内容,然后重试。

companion object : KoinComponent{
private val _authRepository by inject<IAuthRepository>()
private val _personRepository by inject<IPersonRepository>()
private var _clientToken: String? = null

@BeforeClass
@JvmStatic
fun beforeClass() {
startKoin(listOf(AppModule.appModule))
_clientToken = _authRepository.getClientToken()!!.accessToken
}

关于junit - 如何使用 Koin 注入(inject) @BeforeClass 静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54577950/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com