kotlinx.coroutines: Add a a way to disable automatic delay skipping with runBlockingTest

In many cases it would be useful to accurately control time within tests (for example when testing time-based coroutine logic). However, at the moment runBlockingTest seems to enforce delay-skipping behavior.

There does not seem to be a good alternative to this method at the moment if I don’t want delay skipping. I can manually create TestCoroutineScope but that takes some boilerplate and does not bring all the benefits of runBlockingTest (such as making sure all launched tasks have been properly stopped).

At the moment I’m using copy paste version of runBlockingTest with dispatcher.advanceUntilIdle() removed, but that is really bad solution.

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 16 (6 by maintainers)

Commits related to this issue

Most upvoted comments

Let’s say I have simple method like that:

fun CoroutineScope.showAnimationForTwoSeconds() = launch {
    animationController.startAnimation()

    delay(2000)
    animationController.stopAnimation()
}

Then I want to properly test this:

fun testAnimationStart() = runBlockingTest {
    showAnimationForTwoSeconds()
    
    assertThat(animationController).isAnimationRunning()

    advanceTimeBy(2000)
    assertThat(animationController).isAnimationNotRunning()
}

At the moment this test would fail since runBlockingTest skips all delays automatically, which means that stopAnimation call would be made immediatelly, before test can check whether animation is running.