Kotlin coroutine runTest fails with the delay call

316 views Asked by At

When I have a delay call inside a launch, the runTest in unit tests fails.

private val testDispatcher = UnconfinedTestDispatcher()

@Test
fun exampleTest() = runTest(testDispatcher) {
    var result = 0

    val job = launch(testDispatcher) {
        delay(1)
        result = 1
    }

    // advanceUntilIdle()
    println("job.isCompleted: ${job.isCompleted}, result: $result")

    Assert.assertEquals(1, result)
}

The output is job.isCompleted: false, result: 0.

If I remove the delay or uncomment advanceUntilIdle() the test passes, but I cannot get why it is that way.

My thoughts - with that code, I use testDispatcher inside the test and inside launch, so I expect it to skip delays. Where I am wrong?

0

There are 0 answers