使用带有延迟的协程验证在单元测试中调用的方法 [英] Verify method called in unit testing using coroutine with delay

查看:35
本文介绍了使用带有延迟的协程验证在单元测试中调用的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been reading this article to understand how to unit test a coroutine that contains a delay and applied it, but I still don't understand why verify is being called before having called myDelayedMethod() in the coroutine and therefore the verification fails. Isn't there a way to execute the code synchronously in the test?

伪代码:

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()
}

推荐答案

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

One idea could be to return the Job in method1 like the following:

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

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

And then replace method1() with method1().join(), so that runBlockingTest waits for the execution of the coroutine.

这篇关于使用带有延迟的协程验证在单元测试中调用的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆