strok_777
strok_777

Reputation: 1351

Verify method called in unit testing using coroutine with delay

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?

Pseudocode:

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

Upvotes: 2

Views: 1388

Answers (1)

Amit
Amit

Reputation: 669

One approach to execute the test code synchronously is to return the Job in method1 like the following:

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

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

Upvotes: 4

Related Questions