我测试了Architecture Components,JUnit4和Mockito。为了测试LiveData,我需要拥有InstantTaskExecutorRule。
一种JUnit测试规则,该规则将体系结构组件使用的后台执行器与另一个同步执行每个任务的执行器交换。
@RunWith(JUnit4::class)
class MyTest {
@Rule
@JvmField
val rule = InstantTaskExecutorRule()
}
由于InstantTaskExecutorRule,我很难正确测试。我想延迟一个残存的方法响应。
@Test
fun test() {
val underTest = UnderTest(mocked)
val liveData = ...
`when`(mocked.doSomething())
.thenAnswer {
print("a")
Thread.sleep(1000)
print("b")
return liveData
}
// I want call mocked.doSomething() 1 time,
// while underTest.doSomething() is called 3 times.
print("1")
underTest.doSomething()
print("2")
underTest.doSomething()
print("3")
underTest.doSomething()
verify(mocked).doSomething()
}
结果:1ab2ab3ab
期望:123ababab