Dav*_*edy 3 junit static dependency-injection kotlin koin
我有一个集成测试,需要在运行任何后续测试之前调用一次REST服务来获取访问令牌。在将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)
}
Run Code Online (Sandbox Code Playgroud)
AuthRepository和PersonRepository具有其他依赖关系,到目前为止,这些依赖关系都已在其构造函数中实例化。现在,我想使用Koin通过注入存储库来解决这些依赖关系:
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
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试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
Run Code Online (Sandbox Code Playgroud)
我还有其他方法可以使用Koin将类插入@BeforeClass静态方法吗?
小智 5
根据kotlin 文档,伴随对象在技术上是真实的对象。
即使伴随对象的成员看起来像其他语言中的静态成员,在运行时它们仍然是真实对象的实例成员,并且可以例如实现接口:
如果一个类想注入依赖关系,但它不是koin支持的类之一(Activity,Fragment,ViewModel,KoinTest等),则该类应实现KoinComponent接口。
因此,请考虑将伴随对象定义更改为以下内容,然后重试。
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
}
Run Code Online (Sandbox Code Playgroud)