androidunit-testingdelaykotlin-coroutines

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

Solution

  • 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.