testing-coroutines-with-runtest

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Testing Coroutines With runTest — Virtual Time Without Wall Clock

使用 runTest 测试协程——基于虚拟时间,而非真实时间

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
.
runTest
是在 JVM 上测试 suspend 函数以及基于
viewModelScope
的代码的唯一正确入口。本 skill 详细说明了
TestScope
约定、两种
TestDispatcher
、共享的
TestCoroutineScheduler
虚拟时钟,以及防止
Dispatchers.setMain
在测试之间泄漏的
MainDispatcherRule
配置。Flow 专项断言请参阅
../testing-flows-with-turbine/SKILL.md
。

When to use this skill

何时使用此 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.
  • 被测类公开了
    suspend fun
    ,或会向
    viewModelScope
    /
    lifecycleScope
    启动协程。
  • 开发者使用
    runBlocking { … }
    ,导致测试挂起;或者 10 分钟的
    delay
    使测试运行过慢。
  • ViewModel 从协程中依次发出
    Loading -> Success
    ,测试需要断言每个中间状态。
  • 构建输出弃用提示
    runBlockingTest is deprecated. Use runTest
    ,或
    runTest(... dispatchTimeoutMs = ...)
    错误。
  • 测试因
    IllegalStateException: Module with the Main dispatcher is missing
    而失败,因为
    viewModelScope
    将任务路由到了
    Dispatchers.Main
    。
  • 开发者需要推进虚拟时间(
    advanceTimeBy(5.seconds)
    、
    advanceUntilIdle()
    ),以触发超时、重试或防抖逻辑。

When NOT to use this skill

何时不应使用此 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
    .
  • 测试需要断言跨时间产生的
    Flow
    输出。请使用
    ../testing-flows-with-turbine/SKILL.md
    (Turbine 可处理取消机制、冷热 Flow,以及
    awaitItem
    /
    awaitComplete
    )。
  • 测试使用的是 Compose 的
    MainTestClock
    ,而不是
    kotlinx.coroutines.test
    。请使用
    ../../../compose/synchronization/controlling-the-test-clock/SKILL.md
    。
  • 测试通过 AndroidJUnit4 在模拟器或设备上运行。JUnit4 本身的配置请参阅
    ../../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).
  • Gradle:
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.x")
    (
    docs/CORPUS.md
    §G.1)。必须仅使用
    testImplementation
    ,绝不能使用
    implementation
    。该库会安装与
    Dispatchers.setMain
    相关的设施,不适合发布到生产环境。
  • 测试文件需要使用
    @file:OptIn(ExperimentalCoroutinesApi::class)
    (也可按调用启用)。在 1.10.x(R5)中,
    currentTime
    、
    advanceTimeBy
    、
    advanceUntilIdle
    、
    runCurrent
    和 dispatcher 构造函数仍标记为
    @ExperimentalCoroutinesApi
    。
  • 对于 ViewModel 测试,应注入
    CoroutineDispatcher
    (即“DispatcherProvider”),使 SUT 能将任务路由到测试体推进的同一个
    TestCoroutineScheduler
    。硬编码的
    Dispatchers.IO
    /
    Dispatchers.Default
    无法感知虚拟时间。
  • 对于编译到 JS / wasm 的 KMP 库,应使用单表达式形式
    fun foo() = runTest { … }
    ,以便返回对应平台的
    TestResult
    (R5;参见下文“TestResult 约定”)。

runTest signature

runTest 签名

kotlin
public fun runTest(
    context: CoroutineContext = EmptyCoroutineContext,
    timeout: Duration = 60.seconds,
    testBody: suspend TestScope.() -> Unit
): TestResult
(
docs/CORPUS.md
§G.4.) Three things to internalize:
  1. timeout
    is the whole-test deadline, NOT a per-dispatch quiescence timeout. The deprecated
    dispatchTimeoutMs
    overload had different semantics — see migration below.
  2. 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.
  3. Uncaught exceptions in children are aggregated and rethrown as a single failure at the end of the test.
kotlin
public fun runTest(
    context: CoroutineContext = EmptyCoroutineContext,
    timeout: Duration = 60.seconds,
    testBody: suspend TestScope.() -> Unit
): TestResult
(
docs/CORPUS.md
§G.4。)需要牢记三点:
  1. timeout
    是整个测试的截止时间,而不是每次 dispatch 静默阶段的超时时间。已弃用的
    dispatchTimeoutMs
    重载具有不同的语义——参见下文的迁移说明。
  2. testBody
    返回后,
    runTest
    会等待所有在
    TestScope
    上启动的子协程完成。在
    TestScope.backgroundScope
    上启动的子协程则会在测试结束时自动取消。对于热 Flow collector,应使用
    backgroundScope
    。
  3. 子协程中的未捕获异常会被聚合并在测试结束时作为单个失败重新抛出。

TestScope members

TestScope 成员

kotlin
sealed 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
}
Plus library extensions on
TestScope
:
advanceTimeBy(delay)
,
advanceTimeBy(durationMillis)
,
advanceUntilIdle()
,
runCurrent()
. (R5.)
kotlin
sealed 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
}
此外,
TestScope
还有以下库扩展:
advanceTimeBy(delay)
、
advanceTimeBy(durationMillis)
、
advanceUntilIdle()
、
runCurrent()
。(R5。)

TestDispatcher truth table

TestDispatcher 对照表

DispatcherBehaviorPick 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.
Dispatcher行为适用场景
StandardTestDispatcher
将 continuation 排入 scheduler 队列。在调用
runCurrent()
/
advanceTimeBy(...)
/
advanceUntilIdle()
之前,不会执行任何任务。
runTest
的默认选择。
断言中间状态(
Loading
->
Success
);精确控制虚拟时间;无竞态的问题复现。
UnconfinedTestDispatcher
急切执行:
launch { }
会同步运行,直到遇到第一个真实挂起点。
设置热
StateFlow
/
SharedFlow
collector,使首次输出无需显式调用
runCurrent()
即可被观察到。
(
docs/CORPUS.md
§G.5。)
默认使用
StandardTestDispatcher
。
仅当热 Flow collector 的急切执行确实重要,并且能够说明使用理由时,才选择
UnconfinedTestDispatcher
;它会掩盖在
Dispatchers.Default
下运行的生产代码中可能出现的顺序问题。

TestCoroutineScheduler — the virtual clock

TestCoroutineScheduler——虚拟时钟

TestCoroutineScheduler
is the single source of virtual time shared by every
TestDispatcher
participating in a test.
APIEffect
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.
TestCoroutineScheduler
是测试中所有参与工作的
TestDispatcher
共享的唯一虚拟时间来源。
API效果
runCurrent()
执行
currentTime
时已经到期的任务,但不会推进时钟。
advanceTimeBy(delta)
将
currentTime
推进
delta
,并执行所有截止时间已到的任务。
advanceUntilIdle()
循环执行
runCurrent
和时间推进,直到队列为空,即“执行完所有任务”。
currentTime
只读的已流逝虚拟毫秒数。
(R5。)
关键点:
Dispatchers.IO
、
Dispatchers.Default
和任何
newSingleThreadContext(...)
都是真实线程池,不参与虚拟时钟。
withContext(Dispatchers.IO)
内的
delay()
使用真实时间。解决方案是依赖注入——传入一个
CoroutineDispatcher
,并在测试中替换为
mainRule.dispatcher
(或
StandardTestDispatcher(testScheduler)
)。

Dispatchers.setMain / resetMain — required for ViewModels

Dispatchers.setMain / resetMain——ViewModel 测试的必需配置

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
.
Android 的
Dispatchers.Main
是基于主
Looper
的
HandlerContext
,而 JVM 单元测试中不存在主
Looper
。如果未调用
Dispatchers.setMain
,任何通过
viewModelScope
、
lifecycleScope
或
flowOn(Dispatchers.Main)
启动的任务都会抛出
IllegalStateException: Module with the Main dispatcher is missing
。

Canonical MainDispatcherRule (androidx)

标准 MainDispatcherRule(androidx)

Verbatim from
androidx/testutils/testutils-ktx/src/jvmMain/kotlin/androidx/testutils/MainDispatcherRule.jvm.kt
(
docs/CORPUS.md
§G.3):
kotlin
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() }
            }
        }
}
逐字摘自
androidx/testutils/testutils-ktx/src/jvmMain/kotlin/androidx/testutils/MainDispatcherRule.jvm.kt
(
docs/CORPUS.md
§G.3):
kotlin
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

TestWatcher 变体——需要公开 dispatcher 时使用

kotlin
@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()
    }
}
kotlin
@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

用法

kotlin
@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)
    }
}
kotlin
@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)
    }
}

TestResult contract — JVM vs JS

TestResult 约定——JVM 与 JS

kotlin
public expect class TestResult
PlatformActualCaller 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.
kotlin
public expect class TestResult
平台实际类型调用方要求
JVM
Unit
任意方式均可。
Native
Unit
同上。
Kotlin/JS、wasm
Promise<Unit>
测试函数必须
return runTest { … }
。
(R5。)
对于仅支持 Android 的项目,可以编写
@Test fun foo() { runTest { … } }
,因为
TestResult
会折叠为
Unit
。对于 KMP 模块,这种写法会吞掉
Promise<Unit>
,导致 JS 框架无法等待测试完成——因此每次都应编写
@Test fun foo() = runTest { … }
(单表达式形式)。**推荐:**始终使用单表达式形式,以防模块后续增加 KMP target。

Migration from runBlockingTest

从 runBlockingTest 迁移

1.5.x and older1.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.
1.5.x 及更早版本1.7+
runBlockingTest { … }
runTest { … }
TestCoroutineScope
TestScope
TestCoroutineDispatcher
StandardTestDispatcher
/
UnconfinedTestDispatcher
pauseDispatcher { } / resumeDispatcher
已移除——改用显式的
runCurrent
/
advanceTimeBy
cleanupTestCoroutines()
不再需要——
runTest
会处理清理
runTest(... dispatchTimeoutMs = X) { … }
runTest(... timeout = X.milliseconds) { … }
(语义已改变)
runBlockingTest
的弃用级别为 WARNING;
dispatchTimeoutMs
重载的弃用级别为 ERROR(R5;
docs/CORPUS.md
§G.2)。迁移替代方式可以直接机械替换,但超时语义并不完全相同:旧的
dispatchTimeoutMs
表示每次 dispatch 静默阶段的超时,新的
timeout
则表示整个测试的截止时间。

Patterns

模式

Pattern: WRONG —
runBlocking
to test a suspend function

模式:错误——使用 runBlocking 测试 suspend 函数

kotlin
// 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.
kotlin
// 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)
}
kotlin
// 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.
kotlin
// 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)
}

Pattern: WRONG — assert before advancing

模式:错误——推进时间前进行断言

kotlin
// 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.
kotlin
// RIGHT
@Test fun loadsItems() = runTest(mainRule.dispatcher) {
    val vm = MyViewModel(repo, mainRule.dispatcher)
    vm.load()
    advanceUntilIdle()
    assertEquals(items, vm.state.value.items)
}
kotlin
// 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.
kotlin
// RIGHT
@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

模式:错误——在 runTest 中使用 withContext(Dispatchers.IO)

kotlin
// 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.
kotlin
// 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())
}
kotlin
// 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.
kotlin
// 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())
}

Pattern: WRONG — collect on TestScope (test hangs)

模式:错误——在 TestScope 上 collect(测试挂起)

kotlin
// 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.
kotlin
// 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)
}
For Flow assertions specifically, prefer Turbine — see
../testing-flows-with-turbine/SKILL.md
.
kotlin
// 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.
kotlin
// 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)
}
对于 Flow 断言,优先使用 Turbine——参见
../testing-flows-with-turbine/SKILL.md
。

Pattern: the "two schedulers" trap

模式:“两个 scheduler”陷阱

kotlin
// 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.)
kotlin
// 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)
}
(R5 gotcha #4.)
kotlin
// 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.)
kotlin
// 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)
}
(R5 陷阱 #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
    Promise<Unit>
    .
  • PREFERRED: default to
    StandardTestDispatcher
    . Use
    UnconfinedTestDispatcher
    only for hot-flow collector setup where eagerness is the point.
  • PREFERRED:
    kotlinx-coroutines-debug
    on the test classpath so
    runTest
    timeouts include a coroutine stack dump.
  • 必须使用
    runTest { … }
    ,不得使用
    runBlocking { … }
    或已弃用的
    runBlockingTest { … }
    。
  • 必须仅通过
    testImplementation
    依赖
    kotlinx-coroutines-test
    。不得将其放在
    implementation
    中。
  • 必须在使用
    currentTime
    、
    advanceTimeBy
    、
    advanceUntilIdle
    、
    runCurrent
    、
    StandardTestDispatcher(...)
    或
    UnconfinedTestDispatcher(...)
    之前,通过
    @file:OptIn(ExperimentalCoroutinesApi::class)
    (或按调用启用)声明实验性 API 使用许可。
  • 必须为所有 ViewModel/
    viewModelScope
    测试安装
    Dispatchers.setMain(testDispatcher)
    (通过
    MainDispatcherRule
    /
    MainCoroutineRule
    )。并在规则的 finally 块或
    @After
    中重置。
  • 必须将
    mainRule.dispatcher
    传入
    runTest(...)
    ,使
    TestScope
    与 Main 共享同一个 scheduler。否则,
    advanceUntilIdle()
    只会推进其中一个 scheduler。
  • 必须为生产代码中用于 IO/Default 工作的所有
    CoroutineDispatcher
    提供注入方式。硬编码的
    Dispatchers.IO
    即使在
    runTest
    下也会使用真实时间运行。
  • 必须在
    TestScope.backgroundScope
    上启动热 Flow collector(或使用 Turbine)。绝不要直接在
    TestScope
    上调用
    collect
    ——测试会挂起直至 60 秒超时。
  • 不得在未先调用
    advanceUntilIdle()
    的情况下断言状态;对于“当前此刻”的微任务队列,可以调用
    runCurrent()
    。使用
    StandardTestDispatcher
    时,排队中的任务尚未运行。
  • 不得依赖
    runTest(... dispatchTimeoutMs = X)
    ——该参数已被弃用并产生错误。请使用
    timeout = X.milliseconds
    ;同时注意语义已经改变(整个测试的截止时间,而不是每次 dispatch 静默阶段的超时)。
  • **推荐:**在 KMP 的 JS/wasm 平台上使用单表达式形式
    @Test fun foo() = runTest { … }
    ,因为这些平台的
    TestResult
    是
    Promise<Unit>
    。
  • **推荐:**默认使用
    StandardTestDispatcher
    。仅在热 Flow collector 的设置确实需要急切执行时使用
    UnconfinedTestDispatcher
    。
  • **推荐:**在测试 classpath 中加入
    kotlinx-coroutines-debug
    ,以便
    runTest
    超时时输出协程栈转储。

Verification

验证

  • ./gradlew :module:test
    passes with no
    Module with the Main dispatcher is missing
    exception.
  • No
    runBlocking { … }
    or
    runBlockingTest { … }
    calls remain in test sources (
    grep -rn 'runBlocking[^T]' src/test
    ;
    grep -rn 'runBlockingTest' src/test
    ).
  • No
    dispatchTimeoutMs
    parameter remains (
    grep -rn 'dispatchTimeoutMs' src/test
    ).
  • Every ViewModel/
    viewModelScope
    test class declares a
    @get:Rule MainCoroutineRule
    (or equivalent) and passes its
    dispatcher
    into
    runTest(...)
    .
  • Every hot-flow collector in tests uses
    backgroundScope
    or
    flow.test { … }
    (Turbine), never bare
    collect
    on
    TestScope
    .
  • Production classes that use
    Dispatchers.IO
    /
    Dispatchers.Default
    accept an injectable
    CoroutineDispatcher
    and the test substitutes
    mainRule.dispatcher
    .
  • @file:OptIn(ExperimentalCoroutinesApi::class)
    is on every test file using
    advanceTimeBy
    /
    advanceUntilIdle
    /
    runCurrent
    /
    currentTime
    .
  • KMP modules (commonTest) use
    fun foo() = runTest { … }
    single-expression form.
  • ./gradlew :module:test
    通过,且没有
    Module with the Main dispatcher is missing
    异常。
  • 测试源码中不存在任何
    runBlocking { … }
    或
    runBlockingTest { … }
    调用(
    grep -rn 'runBlocking[^T]' src/test
    ;
    grep -rn 'runBlockingTest' src/test
    )。
  • 不存在任何
    dispatchTimeoutMs
    参数(
    grep -rn 'dispatchTimeoutMs' src/test
    )。
  • 每个 ViewModel/
    viewModelScope
    测试类都声明了
    @get:Rule MainCoroutineRule
    (或等效规则),并将其
    dispatcher
    传入
    runTest(...)
    。
  • 测试中的每个热 Flow collector 都使用
    backgroundScope
    或
    flow.test { … }
    (Turbine),绝不在
    TestScope
    上直接调用
    collect
    。
  • 使用
    Dispatchers.IO
    /
    Dispatchers.Default
    的生产类接受可注入的
    CoroutineDispatcher
    ,测试中使用
    mainRule.dispatcher
    替换它。
  • 每个使用
    advanceTimeBy
    /
    advanceUntilIdle
    /
    runCurrent
    /
    currentTime
    的测试文件都有
    @file:OptIn(ExperimentalCoroutinesApi::class)
    。
  • KMP 模块(commonTest)使用
    fun foo() = runTest { … }
    单表达式形式。

References

参考资料

  • JetBrains — kotlinx.coroutines.test: https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-test/
  • JetBrains — runTest: https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/run-test.html
  • JetBrains — TestDispatcher: https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-test-dispatcher/
  • Android Developers — Test Kotlin coroutines on Android: https://developer.android.com/kotlin/coroutines/test
  • Android Developers blog — Coroutines on Android, Part III (testing): https://medium.com/androiddevelopers/coroutines-on-android-part-iii-real-work-2ba8a2ec2f45
  • androidx/testutils/testutils-ktx/src/jvmMain/kotlin/androidx/testutils/MainDispatcherRule.jvm.kt
    — canonical
    MainDispatcherRule
    (
    docs/CORPUS.md
    §G.3).
  • androidx/pdf/.../MainCoroutineRule.kt
    —
    TestWatcher
    flavor that exposes the dispatcher.
  • androidx/navigationevent/...NavigationEventDispatcherTest.kt
    —
    runTest(UnconfinedTestDispatcher())
    +
    launchIn(backgroundScope)
    pattern.
  • androidx/room3/.../InvalidationTrackerTest.kt
    — injecting
    TestScope().coroutineContext
    into the SUT.
  • Sibling:
    ../testing-flows-with-turbine/SKILL.md
    — Flow assertions,
    awaitItem
    /
    awaitComplete
    , hot vs cold cancellation.
  • Sibling:
    ../../mocking/mocking-with-mockito/SKILL.md
    — mocking suspend functions with mockito-kotlin.
  • Sibling:
    ../../mocking/mocking-with-mockk/SKILL.md
    —
    coEvery
    /
    coVerify
    for suspend.
  • Sibling:
    ../../runner/configuring-junit4-on-android/SKILL.md
    — JUnit4 plumbing surrounding
    runTest
    .
  • Sibling:
    ../../robolectric/using-robolectric-correctly/SKILL.md
    — when the SUT needs Android framework on the JVM.
  • Cross-set:
    ../../../fundamentals/strategies/applying-testing-strategies/SKILL.md
    — small/medium/big test sizing.
  • Cross-set:
    ../../../fundamentals/strategies/organizing-test-source-sets/SKILL.md
    — where coroutine tests belong.
  • Cross-set:
    ../../../compose/synchronization/controlling-the-test-clock/SKILL.md
    — Compose's
    MainTestClock
    (separate from
    TestCoroutineScheduler
    ).
  • Cross-set:
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    — when the same SUT runs on a device.
  • Research:
    tasks/research/R5-coroutines-test-turbine.md
    .
  • JetBrains — kotlinx.coroutines.test:https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-test/
  • JetBrains — runTest:https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/run-test.html
  • JetBrains — TestDispatcher:https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-test-dispatcher/
  • Android Developers — 在 Android 上测试 Kotlin 协程:https://developer.android.com/kotlin/coroutines/test
  • Android Developers 博客 — Android 上的协程,第三部分(测试):https://medium.com/androiddevelopers/coroutines-on-android-part-iii-real-work-2ba8a2ec2f45
  • androidx/testutils/testutils-ktx/src/jvmMain/kotlin/androidx/testutils/MainDispatcherRule.jvm.kt
    ——标准
    MainDispatcherRule
    (
    docs/CORPUS.md
    §G.3)。
  • androidx/pdf/.../MainCoroutineRule.kt
    ——公开 dispatcher 的
    TestWatcher
    变体。
  • androidx/navigationevent/...NavigationEventDispatcherTest.kt
    ——
    runTest(UnconfinedTestDispatcher())
    与
    launchIn(backgroundScope)
    模式。
  • androidx/room3/.../InvalidationTrackerTest.kt
    ——将
    TestScope().coroutineContext
    注入 SUT。
  • 同级文档:
    ../testing-flows-with-turbine/SKILL.md
    ——Flow 断言、
    awaitItem
    /
    awaitComplete
    、冷热 Flow 与取消机制。
  • 同级文档:
    ../../mocking/mocking-with-mockito/SKILL.md
    ——使用 mockito-kotlin mock suspend 函数。
  • 同级文档:
    ../../mocking/mocking-with-mockk/SKILL.md
    ——针对 suspend 使用
    coEvery
    /
    coVerify
    。
  • 同级文档:
    ../../runner/configuring-junit4-on-android/SKILL.md
    ——围绕
    runTest
    的 JUnit4 配置。
  • 同级文档:
    ../../robolectric/using-robolectric-correctly/SKILL.md
    ——当 SUT 在 JVM 上需要 Android framework 时使用。
  • 跨集合文档:
    ../../../fundamentals/strategies/applying-testing-strategies/SKILL.md
    ——小型/中型/大型测试的规模划分。
  • 跨集合文档:
    ../../../fundamentals/strategies/organizing-test-source-sets/SKILL.md
    ——协程测试应放置的位置。
  • 跨集合文档:
    ../../../compose/synchronization/controlling-the-test-clock/SKILL.md
    ——Compose 的
    MainTestClock
    (独立于
    TestCoroutineScheduler
    )。
  • 跨集合文档:
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    ——当同一个 SUT 在设备上运行时使用。
  • 研究资料:
    tasks/research/R5-coroutines-test-turbine.md
    。