| name | testing-coroutines-with-runtest |
| description | Use this skill to test suspend functions and coroutine-using classes on the JVM with kotlinx-coroutines-test. Covers runTest, TestScope, StandardTestDispatcher vs UnconfinedTestDispatcher, virtual time via TestCoroutineScheduler (advanceTimeBy, advanceUntilIdle, runCurrent), the canonical MainDispatcherRule wrapper for Dispatchers.setMain/resetMain, the TestResult Promise contract on KMP, and the runBlockingTest -> runTest migration. If the user mentions runTest, runBlockingTest deprecated, advanceUntilIdle, advanceTimeBy, TestScope, StandardTestDispatcher, UnconfinedTestDispatcher, MainDispatcherRule, "Module with the Main dispatcher is missing", "test hangs forever", dispatchTimeoutMs, viewModelScope test, or a ViewModel that posts state from a coroutine, use this skill. |
| license | Apache-2.0. See LICENSE for complete terms. |
| metadata | {"author":"Jaewoong Eum (skydoves)","keywords":["kotlin-coroutines","jvm-testing","run-test","test-scope","test-dispatcher","virtual-time","main-dispatcher-rule","viewmodel-testing","runblockingtest-migration","coroutines-test"]} |
Testing Coroutines With runTest — Virtual Time Without Wall Clock
runTest is the only correct entry point for testing suspend functions and viewModelScope-backed code on the JVM. This skill nails down the TestScope contract, the two TestDispatcher flavors, the shared TestCoroutineScheduler virtual clock, and the MainDispatcherRule plumbing that keeps Dispatchers.setMain from leaking between tests. Flow-specific assertions live in ../testing-flows-with-turbine/SKILL.md.
When to use this skill
- The class under test exposes a
suspend fun or launches into viewModelScope / lifecycleScope.
- The developer reaches for
runBlocking { … } and the test hangs, or a 10-minute delay makes the test slow.
- A ViewModel emits
Loading -> Success from a coroutine and the test needs to assert each intermediate state.
- The build emits the deprecation
runBlockingTest is deprecated. Use runTest or runTest(... dispatchTimeoutMs = ...) errors.
- The test fails with
IllegalStateException: Module with the Main dispatcher is missing because viewModelScope routed work through Dispatchers.Main.
- The developer needs to advance virtual time (
advanceTimeBy(5.seconds), advanceUntilIdle()) to trigger a timeout / retry / debounce.
When NOT to use this skill
- The test asserts
Flow emissions across time. Use ../testing-flows-with-turbine/SKILL.md (Turbine handles cancellation, hot vs cold, awaitItem/awaitComplete).
- The test exercises Compose's
MainTestClock rather than kotlinx.coroutines.test. Use ../../../compose/synchronization/controlling-the-test-clock/SKILL.md.
- The test runs on an emulator/device through AndroidJUnit4. JUnit4 setup itself is
../../runner/configuring-junit4-on-android/SKILL.md.
Prerequisites
- Gradle:
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.x") (docs/CORPUS.md §G.1). MUST be testImplementation only — never implementation. The library installs Dispatchers.setMain plumbing that is unsafe to ship to production.
@file:OptIn(ExperimentalCoroutinesApi::class) (or per-call) on test files. currentTime, advanceTimeBy, advanceUntilIdle, runCurrent, and the dispatcher constructors are still @ExperimentalCoroutinesApi on 1.10.x (R5).
- For ViewModel tests, an injected
CoroutineDispatcher (a "DispatcherProvider") so the SUT can route work onto the same TestCoroutineScheduler the test body advances. Hard-coded Dispatchers.IO / Dispatchers.Default will NOT see virtual time.
- For KMP libraries that compile to JS / wasm, use the single-expression form
fun foo() = runTest { … } so the platform TestResult is returned (R5; see "TestResult contract" below).
runTest signature
public fun runTest(
context: CoroutineContext = EmptyCoroutineContext,
timeout: Duration = 60.seconds,
testBody: suspend TestScope.() -> Unit
): TestResult
(docs/CORPUS.md §G.4.) Three things to internalize:
timeout is the whole-test deadline, NOT a per-dispatch quiescence timeout. The deprecated dispatchTimeoutMs overload had different semantics — see migration below.
- After
testBody returns, runTest waits for every child coroutine launched on TestScope to complete. Children launched on TestScope.backgroundScope are auto-cancelled at end of test instead. Use backgroundScope for hot-flow collectors.
- Uncaught exceptions in children are aggregated and rethrown as a single failure at the end of the test.
TestScope members
sealed interface TestScope : CoroutineScope {
val testScheduler: TestCoroutineScheduler
val backgroundScope: CoroutineScope
val currentTime: Long
val testTimeSource: TimeSource.WithComparableMarks
}
Plus library extensions on TestScope: advanceTimeBy(delay), advanceTimeBy(durationMillis), advanceUntilIdle(), runCurrent(). (R5.)
TestDispatcher truth table
| Dispatcher | Behavior | Pick when |
|---|
StandardTestDispatcher | Queues continuations on the scheduler. Nothing runs until runCurrent()/advanceTimeBy(...)/advanceUntilIdle(). Default for runTest. | Asserting intermediate states (Loading -> Success); precise virtual-time control; race-free repro. |
UnconfinedTestDispatcher | Eager: a launch { } runs synchronously up to its first real suspension. | Hot StateFlow/SharedFlow collector setup so the first emission is observed without explicit runCurrent(). |
(docs/CORPUS.md §G.5.)
Default to StandardTestDispatcher. Reach for UnconfinedTestDispatcher only when collector eagerness genuinely matters and you can defend why; it hides ordering bugs that production code under Dispatchers.Default would lose.
TestCoroutineScheduler — the virtual clock
TestCoroutineScheduler is the single source of virtual time shared by every TestDispatcher participating in a test.
| API | Effect |
|---|
runCurrent() | Drains tasks already due at currentTime. Does NOT advance the clock. |
advanceTimeBy(delta) | Advances currentTime by delta, runs every task whose deadline is reached. |
advanceUntilIdle() | Loops runCurrent + advance until the queue is empty. "Run everything to completion." |
currentTime | Read-only virtual milliseconds elapsed. |
(R5.)
CRITICAL: Dispatchers.IO, Dispatchers.Default, and any newSingleThreadContext(...) are real thread pools and do NOT participate in the virtual clock. delay() inside withContext(Dispatchers.IO) uses real wall-clock time. The fix is dependency injection — pass a CoroutineDispatcher and substitute mainRule.dispatcher (or StandardTestDispatcher(testScheduler)) in tests.
Dispatchers.setMain / resetMain — required for ViewModels
Android's Dispatchers.Main is a HandlerContext over the main Looper that does not exist on a JVM unit test. Anything launched via viewModelScope, lifecycleScope, or flowOn(Dispatchers.Main) will throw IllegalStateException: Module with the Main dispatcher is missing without Dispatchers.setMain.
Canonical MainDispatcherRule (androidx)
Verbatim from androidx/testutils/testutils-ktx/src/jvmMain/kotlin/androidx/testutils/MainDispatcherRule.jvm.kt (docs/CORPUS.md §G.3):
class MainDispatcherRule(
private val dispatcher: CoroutineDispatcher,
) : TestRule {
@OptIn(ExperimentalCoroutinesApi::class)
override fun apply(base: Statement?, description: Description?) =
object : Statement() {
override fun evaluate() {
Dispatchers.setMain(dispatcher)
try { base!!.evaluate() } finally { Dispatchers.resetMain() }
}
}
}
TestWatcher flavor — when you need to expose the dispatcher
@ExperimentalCoroutinesApi
class MainCoroutineRule(
val dispatcher: TestDispatcher = StandardTestDispatcher(),
) : TestWatcher() {
override fun starting(description: Description?) {
super.starting(description); Dispatchers.setMain(dispatcher)
}
override fun finished(description: Description?) {
super.finished(description); Dispatchers.resetMain()
}
}
Usage
@OptIn(ExperimentalCoroutinesApi::class)
class MyVmTest {
@get:Rule val mainRule = MainCoroutineRule()
@Test fun loadsItems() = runTest(mainRule.dispatcher) {
val vm = MyViewModel(repo, mainRule.dispatcher)
vm.load()
runCurrent()
assertEquals(Loading, vm.state.value)
advanceUntilIdle()
assertEquals(Success(items), vm.state.value)
}
}
TestResult contract — JVM vs JS
public expect class TestResult
| Platform | Actual | Caller obligation |
|---|
| JVM | Unit | Anything works. |
| Native | Unit | Same. |
| Kotlin/JS, wasm | Promise<Unit> | Test function MUST return runTest { … }. |
(R5.)
For Android-only projects, you can write @Test fun foo() { runTest { … } } because TestResult collapses to Unit. For a KMP module, that swallows the Promise<Unit> and the JS framework cannot await the test — write @Test fun foo() = runTest { … } (single-expression form) every time. PREFERRED: always use the single-expression form to avoid surprises if the module ever ships KMP targets.
Migration from runBlockingTest
| 1.5.x and older | 1.7+ |
|---|
runBlockingTest { … } | runTest { … } |
TestCoroutineScope | TestScope |
TestCoroutineDispatcher | StandardTestDispatcher / UnconfinedTestDispatcher |
pauseDispatcher { } / resumeDispatcher | gone — explicit runCurrent / advanceTimeBy |
cleanupTestCoroutines() | unnecessary — runTest handles cleanup |
runTest(... dispatchTimeoutMs = X) { … } | runTest(... timeout = X.milliseconds) { … } (semantics changed) |
runBlockingTest is deprecated with WARNING; the dispatchTimeoutMs overload is deprecated with ERROR (R5; docs/CORPUS.md §G.2). The migration replacement is mechanical, but the timeout semantics are not identical: old dispatchTimeoutMs was per-dispatch quiescence, new timeout is the whole-test deadline.
Patterns
Pattern: WRONG — runBlocking to test a suspend function
@Test fun loadsItems() = runBlocking {
val vm = MyViewModel(repo)
vm.load()
Thread.sleep(2_000)
assertEquals(Success(items), vm.state.value)
}
@Test fun loadsItems() = runTest(mainRule.dispatcher) {
val vm = MyViewModel(repo, mainRule.dispatcher)
vm.load()
advanceUntilIdle()
assertEquals(Success(items), vm.state.value)
}
Pattern: WRONG — assert before advancing
@Test fun loadsItems() = runTest(mainRule.dispatcher) {
val vm = MyViewModel(repo, mainRule.dispatcher)
vm.load()
assertEquals(emptyList(), vm.state.value.items)
}
@Test fun loadsItems() = runTest(mainRule.dispatcher) {
val vm = MyViewModel(repo, mainRule.dispatcher)
vm.load()
advanceUntilIdle()
assertEquals(items, vm.state.value.items)
}
Pattern: WRONG — withContext(Dispatchers.IO) under runTest
class Repo {
suspend fun fetch() = withContext(Dispatchers.IO) {
delay(2_000)
api.fetch()
}
}
class Repo(private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO) {
suspend fun fetch() = withContext(ioDispatcher) {
delay(2_000)
api.fetch()
}
}
@Test fun fetchesAfterTwoSeconds() = runTest(mainRule.dispatcher) {
val repo = Repo(ioDispatcher = mainRule.dispatcher)
val deferred = async { repo.fetch() }
advanceTimeBy(2_001)
assertEquals(expected, deferred.await())
}
Pattern: WRONG — collect on TestScope (test hangs)
@Test fun observes() = runTest {
val seen = mutableListOf<Int>()
vm.uiState.collect { seen += it }
assertEquals(listOf(0, 1), seen)
}
@Test fun observes() = runTest(mainRule.dispatcher) {
val seen = mutableListOf<Int>()
vm.uiState
.onEach { seen += it }
.launchIn(backgroundScope)
advanceUntilIdle()
vm.refresh()
advanceUntilIdle()
assertEquals(listOf(0, 1), seen)
}
For Flow assertions specifically, prefer Turbine — see ../testing-flows-with-turbine/SKILL.md.
Pattern: the "two schedulers" trap
@get:Rule val mainRule = MainCoroutineRule()
@Test fun broken() = runTest {
val vm = MyViewModel(repo, mainRule.dispatcher)
vm.load()
advanceUntilIdle()
assertEquals(Success(items), vm.state.value)
}
@Test fun ok() = runTest(mainRule.dispatcher) {
val vm = MyViewModel(repo, mainRule.dispatcher)
vm.load()
advanceUntilIdle()
assertEquals(Success(items), vm.state.value)
}
(R5 gotcha #4.)
Mandatory rules
- MUST use
runTest { … }, not runBlocking { … } or the deprecated runBlockingTest { … }.
- MUST depend on
kotlinx-coroutines-test from testImplementation only. MUST NOT put it on implementation.
- MUST apply
@file:OptIn(ExperimentalCoroutinesApi::class) (or per-call) before using currentTime, advanceTimeBy, advanceUntilIdle, runCurrent, StandardTestDispatcher(...), or UnconfinedTestDispatcher(...).
- MUST install
Dispatchers.setMain(testDispatcher) (via MainDispatcherRule/MainCoroutineRule) for any ViewModel/viewModelScope test. Reset in the rule's finally / @After.
- MUST pass
mainRule.dispatcher into runTest(...) so the TestScope and Main share a single scheduler. Otherwise advanceUntilIdle() only flushes one of them.
- MUST inject any
CoroutineDispatcher your production code uses for IO/Default work. Hard-coded Dispatchers.IO will run in real time even under runTest.
- MUST launch hot-flow collectors on
TestScope.backgroundScope (or use Turbine). Never collect directly on the TestScope — the test hangs to the 60 s timeout.
- MUST NOT assert state without first calling
advanceUntilIdle() (or runCurrent() for the "right now" microtask queue). With StandardTestDispatcher, queued work has not run yet.
- MUST NOT rely on
runTest(... dispatchTimeoutMs = X) — deprecated with error. Use timeout = X.milliseconds; remember the semantics changed (whole-test deadline, not per-dispatch quiescence).
- PREFERRED: the single-expression form
@Test fun foo() = runTest { … } for KMP correctness on JS/wasm where TestResult is .
Verification
References