Skip to content
Tutorials Center
My learning

Topics

Lesson 104 of 134 ยท Coroutines

Testing Coroutines

Learn how to test Kotlin coroutines - runBlocking tests, avoiding real delays, injecting time, a hand-made virtual clock, testing flows and cancellation, and how runTest works in a real project.

Concurrent code is the hardest code to test. A test that sleeps for two seconds to "wait for the result" is slow and, worse, flaky: on a busy build server two seconds is sometimes not enough. Good coroutine tests are fast (no real waiting), deterministic (the same result on every run) and precise (they check the order of events, not just the end result).

This lesson teaches the ideas behind that, with code you can run here. The official test library, kotlinx-coroutines-test, is a separate dependency that this page's runner does not have, so the lesson shows runTest as a read-only example and builds small, runnable stand-ins for its main trick, virtual time. For the basics of tests themselves, see testing in Kotlin. Before this, read cancellation and shared state.

A tiny test harness

Real projects use kotlin.test or JUnit. In a single runnable file we write a few lines of our own: an assertion function and a runner that prints one line per test. Every example below reuses these three pieces.

Kotlin First coroutine tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output shows two PASS lines and one FAIL line with expected <user-8> but was <user-7>. The key tool is runBlocking: a suspend function can only be called from a coroutine, and runBlocking starts one, runs the test body inside it, and returns when everything inside has finished. That makes it a fine entry point for simple tests. Its weaknesses are the topic of the next sections.

Problem 1: real time passes

runBlocking waits for real. A test that calls a function with delay(30_000) in it takes thirty seconds. A suite with a hundred of those is unusable. There are two ways out: do not wait at all, or make the waiting fake.

Inject the pause

The simplest way to get rid of real delays is to pass the pausing behavior in as a parameter. In production the default is delay; in a test you pass a function that does nothing, or that records what was asked.

Kotlin A retry helper with an injectable pause

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Run time is a few milliseconds, but the test proves the important part: the waits are 100, 200 and 400 ms (the backoff doubles), and after the last allowed attempt the error reaches the caller. Notice that the retry class catches CancellationException first and rethrows it. Without that line, a cancelled retry loop would swallow the cancellation and keep going.

Injecting a dependency on time is a design decision, not a testing trick. The same parameter lets you configure the pause in production. Also inject CoroutineDispatchers and CoroutineScopes instead of hardcoding Dispatchers.IO; a test can then pass a controlled one.

A virtual clock you can build yourself

The real runTest goes further: delay itself is replaced by a scheduler with a virtual clock. Time moves only when all coroutines are idle, and then it jumps straight to the next wake-up. A ten-second delay takes microseconds.

We can build the idea in about twenty lines. VirtualTime.sleep parks the caller in a list until advanceBy moves the clock far enough. Everything runs on the single thread of runBlocking, so the order is fully deterministic.

Kotlin A hand-made virtual clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You see the first line print [], the second [beat at 1000, beat at 2000, beat at 3000] and the third one more beat. The test "ran" four virtual seconds in no real time and checked exactly which beat happened at which moment. A real timer-based version of this test would take four seconds and might see a beat at 3001 instead of 3000. This is the benefit that runTest brings to every project.

Problem 2: waiting for "the right moment"

A common wrong fix for async tests is delay(100) "to let the other coroutine finish". Instead of guessing, wait on the event itself. A CompletableDeferred (a promise you complete by hand) or a channel makes the order explicit, and yield() lets other coroutines on the same thread run to their next suspension.

Kotlin Synchronizing with a gate instead of sleeping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The test sees [waiting for the gate] first, then both lines. No sleep, no timing, no guesswork: the order is a fact of the program. The yield() is allowed because everything shares one thread here. With real parallel threads (Dispatchers.Default) you would wait for a signal instead, such as a CompletableDeferred completed by the code under test.

Two more tools of the same family:

  • launch(start = CoroutineStart.UNDISPATCHED) runs the new coroutine immediately, until its first suspension, before launch returns. That removes the need for a yield() after starting.
  • job.join() and deferred.await() wait for the exact thing you care about, instead of for a clock.

Testing cancellation and cleanup

Cancellation is behavior worth pinning down: "when the caller gives up, the worker releases its resources". The test starts the worker, cancels it, and checks the cleanup flag.

Kotlin Test that cleanup runs on cancel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first line prints started = true, cleanedUp = false and the second started = true, cleanedUp = true. UNDISPATCHED guarantees the worker is already running when launch returns, and cancelAndJoin waits until its finally block is done, so reading cleanedUp right after is safe.

Testing flows

A cold flow is easy to test: collect it into a list with toList() and compare. When the flow has pauses inside it, use the same injection idea as before.

Kotlin Collecting a flow into a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The three lines are [3, 2, 1], [10, 9] and sum = 10. The same function would take three seconds with the real delay. For hot flows such as StateFlow (see StateFlow and SharedFlow), a test usually reads .value or collects in a background launch and then cancels the collector at the end.

What runTest looks like in a real project

In a Gradle project you add kotlinx-coroutines-test as a test dependency and write the test like this. This is a read-only example: the library is not available on this site's runner.

Kotlin
// read-only example: needs kotlinx-coroutines-test and kotlin-test on the test classpath
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.Test
import kotlin.test.assertEquals

class HeartbeatTest {
    @Test
    fun beatsEverySecond() = runTest {
        val log = mutableListOf<Long>()
        val job = launch {
            while (true) {
                delay(1_000)
                log += currentTime            // virtual milliseconds
            }
        }
        advanceTimeBy(3_100)                  // moves the virtual clock
        runCurrent()                          // runs tasks that are due right now
        assertEquals(listOf(1_000L, 2_000L, 3_000L), log)
        job.cancel()
    }
}

What the pieces do:

  • runTest runs the body with a TestScope. Inside it, delay does not wait: the scheduler skips ahead to the next wake-up. A test with delay(1_000_000) finishes at once. It also fails the test if a coroutine started in the scope throws and nobody handled it, and it times out after a generous real-time limit so a hung test does not block the build.
  • currentTime is the virtual clock; advanceTimeBy(ms), advanceUntilIdle() and runCurrent() control it manually, like our VirtualTime.advanceBy.
  • StandardTestDispatcher queues coroutines until you run them (predictable ordering); UnconfinedTestDispatcher starts them eagerly, which is closer to what you wrote with UNDISPATCHED.
  • Dispatchers.setMain(testDispatcher) replaces Dispatchers.Main (which does not exist in plain JVM tests) so code that uses it can run.
  • For flows, libraries such as Turbine let you assert emissions one by one. Those are third-party and also read-only here.

runTest only controls time for code that uses the test scheduler. If your function creates its own CoroutineScope(Dispatchers.Default) internally, its delay is real again. This is the strongest reason to inject dispatchers and scopes instead of hardcoding them.

Rules of thumb

  • Never use Thread.sleep or a real delay to wait for another coroutine. Wait on a signal (join, await, a channel, a CompletableDeferred).
  • Inject time, dispatchers and scopes into the classes you want to test.
  • Test the failure paths: a cancelled worker, a timeout, an exception thrown halfway. Concurrency bugs live there.
  • Keep tests free of real threads when you can. Single-threaded, deterministic tests are the ones that never flake.
  • A real race (see shared state) cannot be proven absent by a passing test. Reduce the shared state in the design as well.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is delay(2000) in a test to "wait for the result" a bad idea?

    A fixed sleep wastes time when the work is quick and fails when the machine is slow. Wait for the event itself instead.
  2. 2. What does virtual time (as used by runTest) do?

    The test scheduler keeps its own clock and advances it instantly, so a long delay costs almost no real time.
  3. 3. What is the benefit of launch(start = CoroutineStart.UNDISPATCHED) in a test?

    You know the code before the first suspension point has already run, so you can assert on its effects without a yield() or sleep.
  4. 4. A retry helper takes pause: suspend (Long) -> Unit = { delay(it) } as a parameter. Why?

    Injecting the pause removes real waiting from the test and lets it check the exact backoff values.
  5. 5. Which library provides runTest and advanceTimeBy?

    They live in the separate kotlinx-coroutines-test artifact, added as a test dependency.

Summary

  • Good coroutine tests are fast, deterministic and precise: never wait with real sleeps.
  • runBlocking is a simple entry point for tests; it waits for real, so remove or fake the delays.
  • Inject time (a pause function), dispatchers and scopes so tests can control them.
  • A virtual clock jumps to the next wake-up; runTest provides one with currentTime, advanceTimeBy and runCurrent.
  • Synchronize on events (join, await, CompletableDeferred, channels), start with UNDISPATCHED when you need the first step to have run.
  • Test cancellation, cleanup and failure paths; collect cold flows with toList().

Next: Threads and Java Concurrency