[英]Kodein override binding for AndroidTest
I want to override a Kodein binding by a mock before testing my class.在测试我的课程之前,我想通过模拟覆盖 Kodein 绑定。
There is my Kodein init:有我的 Kodein init:
val kodein = Kodein {
bind<MyRepository>() with provider { MyRepository() }
}
Then my class to test:然后我的班级来测试:
class MyClass {
private val mMyRepository: MyRepository by kodein.instance()
suspend fun sendData() = mMyRepository.sendData()
}
And my test class:还有我的测试课:
@RunWith(AndroidJUnit4::class)
class MyClassTest {
@MockK
lateinit var mMyRepositoryMock: MyRepository
val mMyClass = MyClass()
@Before
fun setUp() {
MockKAnnotations.init(this, relaxUnitFun = true)
}
@Test
fun testSendData() {
coEvery { mMyRepositoryMock.sendData() } returns Unit
runBlocking {
mMyClass.sendData()
.collect {
assertTrue(true)
}
}
}
}
I want to override mMyRepository
value in MyClass
during my test by mMyRepositoryMock
.我想在测试期间通过
mMyRepositoryMock
覆盖MyClass
中的mMyRepository
值。
Can somebody help me doing it?有人可以帮我做吗?
This is precisely why we do not recommend using a global Kodein instance.这正是我们不建议使用全局 Kodein 实例的原因。
The best way to ensure a class testability is to remove its context dependency.确保类可测试性的最佳方法是删除其上下文相关性。
Consider the following class:考虑以下类:
class MyClass(override val kodein: Kodein) {
private val mMyRepository: MyRepository by kodein.instance()
suspend fun sendData() = mMyRepository.sendData()
}
Now the kodein
it uses is passed as parameter, and can therefore be properly configured for tests:现在它使用的
kodein
作为参数传递,因此可以为测试正确配置:
@RunWith(AndroidJUnit4::class)
class MyClassTest {
@MockK
lateinit var mMyRepositoryMock: MyRepository
val kodein by Kodein.lazy {
bind<MyRepository>() with provider { mMyRepositoryMock }
}
val mMyClass by lazy { MyClass(kodein) }
@Before
fun setUp() {
MockKAnnotations.init(this, relaxUnitFun = true)
}
@Test
fun testSendData() {
coEvery { mMyRepositoryMock.sendData() } returns Unit
runBlocking {
mMyClass.sendData()
.collect {
assertTrue(true)
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.