我可以在InstantTaskExecutorRule下创建另一个线程吗?

时间:2018-11-26 07:39:26

标签: android-testing junit-rule

我测试了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()
}

结果:1​​ab2ab3ab

期望:123ababab

0 个答案:

没有答案