A test dispatcher schedules coroutines under controlled execution, allowing coroutine tests to use virtual time instead of waiting through real delays. runTest supplies this dispatcher together with a scheduler that fast-forwards delays. section 18.5.1
Listing 18.11 Running a test with virtual time
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.*
import kotlin.time.Duration.Companion.seconds
class PlaygroundTest {
@Test
fun testDelay() = runTest {
val startTime = System.currentTimeMillis()
delay(20.seconds)
println(System.currentTimeMillis() - startTime)
// 11
}
}
A compact test demonstrates that a 20-second coroutine delay completes almost immediately when runTest uses virtual time. section 18.5.1
Use the dispatcher’s execution model deliberately:
- Treat runTest as single-threaded by default: child coroutines can execute concurrently but do not run in parallel with the test body. section 18.5.1
- Provide suspension points such as delay or yield before asserting results from launched coroutines; otherwise those coroutines may not run yet. section 18.5.1
- Control progress with the scheduler: use runCurrent for immediately scheduled work and advanceUntilIdle for all scheduled work. section 18.5.1 section 18.6
Advancing virtual time
A test can launch coroutines delayed by 500 milliseconds and one second, then advance its virtual clock in stages to assert which work has completed. Calling advanceUntilIdle runs every remaining scheduled coroutine. section 18.5.1
