Loading...
Loading...
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.
npx skill4agent add skydoves/android-testing-skills testing-coroutines-with-runtestrunTestviewModelScopeTestScopeTestDispatcherTestCoroutineSchedulerMainDispatcherRuleDispatchers.setMain../testing-flows-with-turbine/SKILL.mdsuspend funviewModelScopelifecycleScoperunBlocking { … }delayLoading -> SuccessrunBlockingTest is deprecated. Use runTestrunTest(... dispatchTimeoutMs = ...)IllegalStateException: Module with the Main dispatcher is missingviewModelScopeDispatchers.MainadvanceTimeBy(5.seconds)advanceUntilIdle()Flow../testing-flows-with-turbine/SKILL.mdawaitItemawaitCompleteMainTestClockkotlinx.coroutines.test../../../compose/synchronization/controlling-the-test-clock/SKILL.md../../runner/configuring-junit4-on-android/SKILL.mdtestImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.x")docs/CORPUS.mdtestImplementationimplementationDispatchers.setMain@file:OptIn(ExperimentalCoroutinesApi::class)currentTimeadvanceTimeByadvanceUntilIdlerunCurrent@ExperimentalCoroutinesApiCoroutineDispatcherTestCoroutineSchedulerDispatchers.IODispatchers.Defaultfun foo() = runTest { … }TestResultpublic fun runTest(
context: CoroutineContext = EmptyCoroutineContext,
timeout: Duration = 60.seconds,
testBody: suspend TestScope.() -> Unit
): TestResultdocs/CORPUS.mdtimeoutdispatchTimeoutMstestBodyrunTestTestScopeTestScope.backgroundScopebackgroundScopesealed interface TestScope : CoroutineScope {
val testScheduler: TestCoroutineScheduler // shared virtual clock
val backgroundScope: CoroutineScope // children auto-cancelled at test end
val currentTime: Long // virtual ms elapsed
val testTimeSource: TimeSource.WithComparableMarks
}TestScopeadvanceTimeBy(delay)advanceTimeBy(durationMillis)advanceUntilIdle()runCurrent()| Dispatcher | Behavior | Pick when |
|---|---|---|
| Queues continuations on the scheduler. Nothing runs until | Asserting intermediate states ( |
| Eager: a | Hot |
docs/CORPUS.mdStandardTestDispatcherUnconfinedTestDispatcherDispatchers.DefaultTestCoroutineSchedulerTestDispatcher| API | Effect |
|---|---|
| Drains tasks already due at |
| Advances |
| Loops |
| Read-only virtual milliseconds elapsed. |
Dispatchers.IODispatchers.DefaultnewSingleThreadContext(...)delay()withContext(Dispatchers.IO)CoroutineDispatchermainRule.dispatcherStandardTestDispatcher(testScheduler)Dispatchers.MainHandlerContextLooperviewModelScopelifecycleScopeflowOn(Dispatchers.Main)IllegalStateException: Module with the Main dispatcher is missingDispatchers.setMainandroidx/testutils/testutils-ktx/src/jvmMain/kotlin/androidx/testutils/MainDispatcherRule.jvm.ktdocs/CORPUS.mdclass 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() }
}
}
}@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()
}
}@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() // see Loading state
assertEquals(Loading, vm.state.value)
advanceUntilIdle() // run network/db
assertEquals(Success(items), vm.state.value)
}
}public expect class TestResult| Platform | Actual | Caller obligation |
|---|---|---|
| JVM | | Anything works. |
| Native | | Same. |
| Kotlin/JS, wasm | | Test function MUST |
@Test fun foo() { runTest { … } }TestResultUnitPromise<Unit>@Test fun foo() = runTest { … }| 1.5.x and older | 1.7+ |
|---|---|
| |
| |
| |
| gone — explicit |
| unnecessary — |
| |
runBlockingTestdispatchTimeoutMsdocs/CORPUS.mddispatchTimeoutMstimeoutrunBlocking// WRONG
@Test fun loadsItems() = runBlocking {
val vm = MyViewModel(repo)
vm.load()
Thread.sleep(2_000) // wait for the launch
assertEquals(Success(items), vm.state.value)
}
// WRONG because: runBlocking has no virtual time and no exception aggregation. The
// delay in load() runs in real time; the launch may not have completed; uncaught
// exceptions in children are silently swallowed.// RIGHT
@Test fun loadsItems() = runTest(mainRule.dispatcher) {
val vm = MyViewModel(repo, mainRule.dispatcher)
vm.load()
advanceUntilIdle() // virtual time flushes everything
assertEquals(Success(items), vm.state.value)
}// WRONG
@Test fun loadsItems() = runTest(mainRule.dispatcher) {
val vm = MyViewModel(repo, mainRule.dispatcher)
vm.load()
assertEquals(emptyList(), vm.state.value.items) // "passes" trivially
}
// WRONG because: with StandardTestDispatcher (the default), nothing runs until you
// advance. The launch inside vm.load() is queued but has not executed. The test
// passes for the wrong reason — the items list is empty because load() never ran.// RIGHT
@Test fun loadsItems() = runTest(mainRule.dispatcher) {
val vm = MyViewModel(repo, mainRule.dispatcher)
vm.load()
advanceUntilIdle()
assertEquals(items, vm.state.value.items)
}// WRONG: production code
class Repo {
suspend fun fetch() = withContext(Dispatchers.IO) {
delay(2_000) // real wall-clock time
api.fetch()
}
}
// WRONG because: Dispatchers.IO is a real thread pool. delay(2_000) takes 2 seconds
// of real time. advanceTimeBy(2_000) does NOT skip it. The whole test runs in real
// time and may exceed the 60s runTest timeout.// RIGHT: production code
class Repo(private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO) {
suspend fun fetch() = withContext(ioDispatcher) {
delay(2_000)
api.fetch()
}
}
// RIGHT: test
@Test fun fetchesAfterTwoSeconds() = runTest(mainRule.dispatcher) {
val repo = Repo(ioDispatcher = mainRule.dispatcher) // shares scheduler
val deferred = async { repo.fetch() }
advanceTimeBy(2_001) // virtual; instant in real time
assertEquals(expected, deferred.await())
}// WRONG
@Test fun observes() = runTest {
val seen = mutableListOf<Int>()
vm.uiState.collect { seen += it } // never returns
assertEquals(listOf(0, 1), seen) // unreachable
}
// WRONG because: vm.uiState is a hot StateFlow. collect on the test's TestScope
// never completes; runTest waits for child completion and hangs until the 60s
// timeout fires. Use backgroundScope (auto-cancelled at end of test) — or Turbine.// RIGHT — backgroundScope
@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)
}../testing-flows-with-turbine/SKILL.md// WRONG
@get:Rule val mainRule = MainCoroutineRule() // scheduler A
@Test fun broken() = runTest { // scheduler B (auto-created)
val vm = MyViewModel(repo, mainRule.dispatcher) // posts to A
vm.load()
advanceUntilIdle() // flushes B only — A's work pending
assertEquals(Success(items), vm.state.value) // FAIL: still Loading
}
// WRONG because: by default runTest creates its own StandardTestDispatcher with a
// fresh TestCoroutineScheduler. mainRule's dispatcher has a different scheduler;
// advanceUntilIdle() only flushes the test body's scheduler. (Recent kotlinx-
// coroutines-test versions do try to reuse Main's scheduler when Main was replaced
// with a TestDispatcher BEFORE runTest starts, but the defensive contract — pass
// the dispatcher explicitly — never breaks across versions.)// RIGHT — share the scheduler explicitly
@Test fun ok() = runTest(mainRule.dispatcher) {
val vm = MyViewModel(repo, mainRule.dispatcher)
vm.load()
advanceUntilIdle()
assertEquals(Success(items), vm.state.value)
}runTest { … }runBlocking { … }runBlockingTest { … }kotlinx-coroutines-testtestImplementationimplementation@file:OptIn(ExperimentalCoroutinesApi::class)currentTimeadvanceTimeByadvanceUntilIdlerunCurrentStandardTestDispatcher(...)UnconfinedTestDispatcher(...)Dispatchers.setMain(testDispatcher)MainDispatcherRuleMainCoroutineRuleviewModelScope@AftermainRule.dispatcherrunTest(...)TestScopeadvanceUntilIdle()CoroutineDispatcherDispatchers.IOrunTestTestScope.backgroundScopecollectTestScopeadvanceUntilIdle()runCurrent()StandardTestDispatcherrunTest(... dispatchTimeoutMs = X)timeout = X.milliseconds@Test fun foo() = runTest { … }TestResultPromise<Unit>StandardTestDispatcherUnconfinedTestDispatcherkotlinx-coroutines-debugrunTest./gradlew :module:testModule with the Main dispatcher is missingrunBlocking { … }runBlockingTest { … }grep -rn 'runBlocking[^T]' src/testgrep -rn 'runBlockingTest' src/testdispatchTimeoutMsgrep -rn 'dispatchTimeoutMs' src/testviewModelScope@get:Rule MainCoroutineRuledispatcherrunTest(...)backgroundScopeflow.test { … }collectTestScopeDispatchers.IODispatchers.DefaultCoroutineDispatchermainRule.dispatcher@file:OptIn(ExperimentalCoroutinesApi::class)advanceTimeByadvanceUntilIdlerunCurrentcurrentTimefun foo() = runTest { … }androidx/testutils/testutils-ktx/src/jvmMain/kotlin/androidx/testutils/MainDispatcherRule.jvm.ktMainDispatcherRuledocs/CORPUS.mdandroidx/pdf/.../MainCoroutineRule.ktTestWatcherandroidx/navigationevent/...NavigationEventDispatcherTest.ktrunTest(UnconfinedTestDispatcher())launchIn(backgroundScope)androidx/room3/.../InvalidationTrackerTest.ktTestScope().coroutineContext../testing-flows-with-turbine/SKILL.mdawaitItemawaitComplete../../mocking/mocking-with-mockito/SKILL.md../../mocking/mocking-with-mockk/SKILL.mdcoEverycoVerify../../runner/configuring-junit4-on-android/SKILL.mdrunTest../../robolectric/using-robolectric-correctly/SKILL.md../../../fundamentals/strategies/applying-testing-strategies/SKILL.md../../../fundamentals/strategies/organizing-test-source-sets/SKILL.md../../../compose/synchronization/controlling-the-test-clock/SKILL.mdMainTestClockTestCoroutineScheduler../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.mdtasks/research/R5-coroutines-test-turbine.md