liveBook · Manning

Test dispatcher

As explained in Kotlin in Action, 2E

A test dispatcher is a coroutine dispatcher that schedules test coroutines, typically under controlled and often single-threaded execution.

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

How Kotlin in Action, 2E covers it

How deep it goes
Explains virtual-time scheduling, single-threaded execution, suspension points, and scheduler controls, but not dispatcher implementation internals.
Examples
Uses delayed increments, currentTime, runCurrent, and advanceUntilIdle to demonstrate staged and complete coroutine execution.
What it assumes
Assumes familiarity with coroutine suspension points and basic coroutine tests, while reinforcing their effect on single-threaded scheduling.
What you can do after
Diagnose coroutine test timing and control execution with virtual time, runCurrent, and advanceUntilIdle.
How it connects
Connects test dispatchers with runTest, virtual time, TestCoroutineScheduler, suspension points, and coroutine testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.