【问题标题】:Verify method called in unit testing using coroutine with delay使用带有延迟的协程验证单元测试中调用的方法
【发布时间】:2021-08-28 13:20:42
【问题描述】:

我一直在阅读 this article 以了解如何对包含延迟的协程进行单元测试并应用它,但我仍然不明白为什么在协程中调用 myDelayedMethod() 之前调用 verify因此验证失败。有没有办法在测试中同步执行代码?

伪代码:

class ClasUnderTest{

  fun method1(){
      GlobalScope.launch {
      myDelayedMethod()
    }
  }

  suspend fun myDelayedMethod(): String{
    withContext(dispatchers.default()){
      delay(X)
      ...
      someClass.someMethod()
   }
  }
}

@Test
fun myTest()= coroutinesTestRule.testDispatcher.runBlockingTest {
  val someClassMock = mock(SomeClass::class.java)
  val myObject = ClasUnderTest(someClassMock) 
  method1()
  verify(someClassMock).someMethod()
}

【问题讨论】:

    标签: android unit-testing delay kotlin-coroutines


    【解决方案1】:

    一个想法可能是在method1 中返回Job,如下所示:

    fun method1(): Job {
      return GlobalScope.launch {
        myDelayedMethod()
      }
    }
    

    然后将method1()替换为method1().join(),让runBlockingTest等待协程的执行。

    【讨论】:

    • 我试过了,但我得到了一个异常通知“java.lang.IllegalStateException:这项工作还没有完成”
    • 除了确保要测试的代码使用 TestCoroutineScope() 作为 CoroutineContext 和 TestCoroutineDispatcher 作为 Dispatcher 之外,这还有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 2019-11-19
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多