testing-coroutines-with-runtest
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTesting Coroutines With runTest — Virtual Time Without Wall Clock
使用 runTest 测试协程——基于虚拟时间,而非真实时间
runTestviewModelScopeTestScopeTestDispatcherTestCoroutineSchedulerMainDispatcherRuleDispatchers.setMain../testing-flows-with-turbine/SKILL.mdrunTestviewModelScopeTestScopeTestDispatcherTestCoroutineSchedulerDispatchers.setMainMainDispatcherRule../testing-flows-with-turbine/SKILL.mdWhen to use this skill
何时使用此 skill
- The class under test exposes a or launches into
suspend fun/viewModelScope.lifecycleScope - The developer reaches for and the test hangs, or a 10-minute
runBlocking { … }makes the test slow.delay - A ViewModel emits from a coroutine and the test needs to assert each intermediate state.
Loading -> Success - The build emits the deprecation or
runBlockingTest is deprecated. Use runTesterrors.runTest(... dispatchTimeoutMs = ...) - The test fails with because
IllegalStateException: Module with the Main dispatcher is missingrouted work throughviewModelScope.Dispatchers.Main - The developer needs to advance virtual time (,
advanceTimeBy(5.seconds)) to trigger a timeout / retry / debounce.advanceUntilIdle()
- 被测类公开了 ,或会向
suspend fun/viewModelScope启动协程。lifecycleScope - 开发者使用 ,导致测试挂起;或者 10 分钟的
runBlocking { … }使测试运行过慢。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 emissions across time. Use
Flow(Turbine handles cancellation, hot vs cold,../testing-flows-with-turbine/SKILL.md/awaitItem).awaitComplete - The test exercises Compose's rather than
MainTestClock. Usekotlinx.coroutines.test.../../../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(Turbine 可处理取消机制、冷热 Flow,以及../testing-flows-with-turbine/SKILL.md/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")§G.1). MUST bedocs/CORPUS.mdonly — nevertestImplementation. The library installsimplementationplumbing that is unsafe to ship to production.Dispatchers.setMain - (or per-call) on test files.
@file:OptIn(ExperimentalCoroutinesApi::class),currentTime,advanceTimeBy,advanceUntilIdle, and the dispatcher constructors are stillrunCurrenton 1.10.x (R5).@ExperimentalCoroutinesApi - For ViewModel tests, an injected (a "DispatcherProvider") so the SUT can route work onto the same
CoroutineDispatcherthe test body advances. Hard-codedTestCoroutineScheduler/Dispatchers.IOwill NOT see virtual time.Dispatchers.Default - For KMP libraries that compile to JS / wasm, use the single-expression form so the platform
fun foo() = runTest { … }is returned (R5; see "TestResult contract" below).TestResult
- Gradle:(
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.x")§G.1)。必须仅使用docs/CORPUS.md,绝不能使用testImplementation。该库会安装与implementation相关的设施,不适合发布到生产环境。Dispatchers.setMain - 测试文件需要使用 (也可按调用启用)。在 1.10.x(R5)中,
@file:OptIn(ExperimentalCoroutinesApi::class)、currentTime、advanceTimeBy、advanceUntilIdle和 dispatcher 构造函数仍标记为runCurrent。@ExperimentalCoroutinesApi - 对于 ViewModel 测试,应注入 (即“DispatcherProvider”),使 SUT 能将任务路由到测试体推进的同一个
CoroutineDispatcher。硬编码的TestCoroutineScheduler/Dispatchers.IO无法感知虚拟时间。Dispatchers.Default - 对于编译到 JS / wasm 的 KMP 库,应使用单表达式形式 ,以便返回对应平台的
fun foo() = runTest { … }(R5;参见下文“TestResult 约定”)。TestResult
runTest signature
runTest 签名
kotlin
public fun runTest(
context: CoroutineContext = EmptyCoroutineContext,
timeout: Duration = 60.seconds,
testBody: suspend TestScope.() -> Unit
): TestResult( §G.4.) Three things to internalize:
docs/CORPUS.md- is the whole-test deadline, NOT a per-dispatch quiescence timeout. The deprecated
timeoutoverload had different semantics — see migration below.dispatchTimeoutMs - After returns,
testBodywaits for every child coroutine launched onrunTestto complete. Children launched onTestScopeare auto-cancelled at end of test instead. UseTestScope.backgroundScopefor hot-flow collectors.backgroundScope - 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( §G.4。)需要牢记三点:
docs/CORPUS.md- 是整个测试的截止时间,而不是每次 dispatch 静默阶段的超时时间。已弃用的
timeout重载具有不同的语义——参见下文的迁移说明。dispatchTimeoutMs - 返回后,
testBody会等待所有在runTest上启动的子协程完成。在TestScope上启动的子协程则会在测试结束时自动取消。对于热 Flow collector,应使用TestScope.backgroundScope。backgroundScope - 子协程中的未捕获异常会被聚合并在测试结束时作为单个失败重新抛出。
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 : , , , . (R5.)
TestScopeadvanceTimeBy(delay)advanceTimeBy(durationMillis)advanceUntilIdle()runCurrent()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
}此外, 还有以下库扩展:、、、。(R5。)
TestScopeadvanceTimeBy(delay)advanceTimeBy(durationMillis)advanceUntilIdle()runCurrent()TestDispatcher truth table
TestDispatcher 对照表
| Dispatcher | Behavior | Pick when |
|---|---|---|
| Queues continuations on the scheduler. Nothing runs until | Asserting intermediate states ( |
| Eager: a | Hot |
( §G.5.)
docs/CORPUS.mdDefault to . Reach for only when collector eagerness genuinely matters and you can defend why; it hides ordering bugs that production code under would lose.
StandardTestDispatcherUnconfinedTestDispatcherDispatchers.Default| Dispatcher | 行为 | 适用场景 |
|---|---|---|
| 将 continuation 排入 scheduler 队列。在调用 | 断言中间状态( |
| 急切执行: | 设置热 |
( §G.5。)
docs/CORPUS.md默认使用 。 仅当热 Flow collector 的急切执行确实重要,并且能够说明使用理由时,才选择 ;它会掩盖在 下运行的生产代码中可能出现的顺序问题。
StandardTestDispatcherUnconfinedTestDispatcherDispatchers.DefaultTestCoroutineScheduler — the virtual clock
TestCoroutineScheduler——虚拟时钟
TestCoroutineSchedulerTestDispatcher| API | Effect |
|---|---|
| Drains tasks already due at |
| Advances |
| Loops |
| Read-only virtual milliseconds elapsed. |
(R5.)
CRITICAL: , , and any are real thread pools and do NOT participate in the virtual clock. inside uses real wall-clock time. The fix is dependency injection — pass a and substitute (or ) in tests.
Dispatchers.IODispatchers.DefaultnewSingleThreadContext(...)delay()withContext(Dispatchers.IO)CoroutineDispatchermainRule.dispatcherStandardTestDispatcher(testScheduler)TestCoroutineSchedulerTestDispatcher| API | 效果 |
|---|---|
| 执行 |
| 将 |
| 循环执行 |
| 只读的已流逝虚拟毫秒数。 |
(R5。)
关键点:、 和任何 都是真实线程池,不参与虚拟时钟。 内的 使用真实时间。解决方案是依赖注入——传入一个 ,并在测试中替换为 (或 )。
Dispatchers.IODispatchers.DefaultnewSingleThreadContext(...)withContext(Dispatchers.IO)delay()CoroutineDispatchermainRule.dispatcherStandardTestDispatcher(testScheduler)Dispatchers.setMain / resetMain — required for ViewModels
Dispatchers.setMain / resetMain——ViewModel 测试的必需配置
Android's is a over the main that does not exist on a JVM unit test. Anything launched via , , or will throw without .
Dispatchers.MainHandlerContextLooperviewModelScopelifecycleScopeflowOn(Dispatchers.Main)IllegalStateException: Module with the Main dispatcher is missingDispatchers.setMainAndroid 的 是基于主 的 ,而 JVM 单元测试中不存在主 。如果未调用 ,任何通过 、 或 启动的任务都会抛出 。
Dispatchers.MainLooperHandlerContextLooperDispatchers.setMainviewModelScopelifecycleScopeflowOn(Dispatchers.Main)IllegalStateException: Module with the Main dispatcher is missingCanonical MainDispatcherRule (androidx)
标准 MainDispatcherRule(androidx)
Verbatim from ( §G.3):
androidx/testutils/testutils-ktx/src/jvmMain/kotlin/androidx/testutils/MainDispatcherRule.jvm.ktdocs/CORPUS.mdkotlin
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() }
}
}
}逐字摘自 ( §G.3):
androidx/testutils/testutils-ktx/src/jvmMain/kotlin/androidx/testutils/MainDispatcherRule.jvm.ktdocs/CORPUS.mdkotlin
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| Platform | Actual | Caller obligation |
|---|---|---|
| JVM | | Anything works. |
| Native | | Same. |
| Kotlin/JS, wasm | | Test function MUST |
(R5.)
For Android-only projects, you can write because collapses to . For a KMP module, that swallows the and the JS framework cannot await the test — write (single-expression form) every time. PREFERRED: always use the single-expression form to avoid surprises if the module ever ships KMP targets.
@Test fun foo() { runTest { … } }TestResultUnitPromise<Unit>@Test fun foo() = runTest { … }kotlin
public expect class TestResult| 平台 | 实际类型 | 调用方要求 |
|---|---|---|
| JVM | | 任意方式均可。 |
| Native | | 同上。 |
| Kotlin/JS、wasm | | 测试函数必须 |
(R5。)
对于仅支持 Android 的项目,可以编写 ,因为 会折叠为 。对于 KMP 模块,这种写法会吞掉 ,导致 JS 框架无法等待测试完成——因此每次都应编写 (单表达式形式)。**推荐:**始终使用单表达式形式,以防模块后续增加 KMP target。
@Test fun foo() { runTest { … } }TestResultUnitPromise<Unit>@Test fun foo() = runTest { … }Migration from runBlockingTest
从 runBlockingTest 迁移
| 1.5.x and older | 1.7+ |
|---|---|
| |
| |
| |
| gone — explicit |
| unnecessary — |
| |
runBlockingTestdispatchTimeoutMsdocs/CORPUS.mddispatchTimeoutMstimeout| 1.5.x 及更早版本 | 1.7+ |
|---|---|
| |
| |
| |
| 已移除——改用显式的 |
| 不再需要—— |
| |
runBlockingTestdispatchTimeoutMsdocs/CORPUS.mddispatchTimeoutMstimeoutPatterns
模式
Pattern: WRONG — runBlocking
to test a suspend function
runBlocking模式:错误——使用 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.mdkotlin
// 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.mdPattern: 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 , not
runTest { … }or the deprecatedrunBlocking { … }.runBlockingTest { … } - MUST depend on from
kotlinx-coroutines-testonly. MUST NOT put it ontestImplementation.implementation - MUST apply (or per-call) before using
@file:OptIn(ExperimentalCoroutinesApi::class),currentTime,advanceTimeBy,advanceUntilIdle,runCurrent, orStandardTestDispatcher(...).UnconfinedTestDispatcher(...) - MUST install (via
Dispatchers.setMain(testDispatcher)/MainDispatcherRule) for any ViewModel/MainCoroutineRuletest. Reset in the rule's finally /viewModelScope.@After - MUST pass into
mainRule.dispatcherso therunTest(...)and Main share a single scheduler. OtherwiseTestScopeonly flushes one of them.advanceUntilIdle() - MUST inject any your production code uses for IO/Default work. Hard-coded
CoroutineDispatcherwill run in real time even underDispatchers.IO.runTest - MUST launch hot-flow collectors on (or use Turbine). Never
TestScope.backgroundScopedirectly on thecollect— the test hangs to the 60 s timeout.TestScope - MUST NOT assert state without first calling (or
advanceUntilIdle()for the "right now" microtask queue). WithrunCurrent(), queued work has not run yet.StandardTestDispatcher - MUST NOT rely on — deprecated with error. Use
runTest(... dispatchTimeoutMs = X); remember the semantics changed (whole-test deadline, not per-dispatch quiescence).timeout = X.milliseconds - PREFERRED: the single-expression form for KMP correctness on JS/wasm where
@Test fun foo() = runTest { … }isTestResult.Promise<Unit> - PREFERRED: default to . Use
StandardTestDispatcheronly for hot-flow collector setup where eagerness is the point.UnconfinedTestDispatcher - PREFERRED: on the test classpath so
kotlinx-coroutines-debugtimeouts include a coroutine stack dump.runTest
- 必须使用 ,不得使用
runTest { … }或已弃用的runBlocking { … }。runBlockingTest { … } - 必须仅通过 依赖
testImplementation。不得将其放在kotlinx-coroutines-test中。implementation - 必须在使用 、
currentTime、advanceTimeBy、advanceUntilIdle、runCurrent或StandardTestDispatcher(...)之前,通过UnconfinedTestDispatcher(...)(或按调用启用)声明实验性 API 使用许可。@file:OptIn(ExperimentalCoroutinesApi::class) - 必须为所有 ViewModel/测试安装
viewModelScope(通过Dispatchers.setMain(testDispatcher)/MainDispatcherRule)。并在规则的 finally 块或MainCoroutineRule中重置。@After - 必须将 传入
mainRule.dispatcher,使runTest(...)与 Main 共享同一个 scheduler。否则,TestScope只会推进其中一个 scheduler。advanceUntilIdle() - 必须为生产代码中用于 IO/Default 工作的所有 提供注入方式。硬编码的
CoroutineDispatcher即使在Dispatchers.IO下也会使用真实时间运行。runTest - 必须在 上启动热 Flow collector(或使用 Turbine)。绝不要直接在
TestScope.backgroundScope上调用TestScope——测试会挂起直至 60 秒超时。collect - 不得在未先调用 的情况下断言状态;对于“当前此刻”的微任务队列,可以调用
advanceUntilIdle()。使用runCurrent()时,排队中的任务尚未运行。StandardTestDispatcher - 不得依赖 ——该参数已被弃用并产生错误。请使用
runTest(... dispatchTimeoutMs = X);同时注意语义已经改变(整个测试的截止时间,而不是每次 dispatch 静默阶段的超时)。timeout = X.milliseconds - **推荐:**在 KMP 的 JS/wasm 平台上使用单表达式形式 ,因为这些平台的
@Test fun foo() = runTest { … }是TestResult。Promise<Unit> - **推荐:**默认使用 。仅在热 Flow collector 的设置确实需要急切执行时使用
StandardTestDispatcher。UnconfinedTestDispatcher - **推荐:**在测试 classpath 中加入 ,以便
kotlinx-coroutines-debug超时时输出协程栈转储。runTest
Verification
验证
- passes with no
./gradlew :module:testexception.Module with the Main dispatcher is missing - No or
runBlocking { … }calls remain in test sources (runBlockingTest { … };grep -rn 'runBlocking[^T]' src/test).grep -rn 'runBlockingTest' src/test - No parameter remains (
dispatchTimeoutMs).grep -rn 'dispatchTimeoutMs' src/test - Every ViewModel/test class declares a
viewModelScope(or equivalent) and passes its@get:Rule MainCoroutineRuleintodispatcher.runTest(...) - Every hot-flow collector in tests uses or
backgroundScope(Turbine), never bareflow.test { … }oncollect.TestScope - Production classes that use /
Dispatchers.IOaccept an injectableDispatchers.Defaultand the test substitutesCoroutineDispatcher.mainRule.dispatcher - is on every test file using
@file:OptIn(ExperimentalCoroutinesApi::class)/advanceTimeBy/advanceUntilIdle/runCurrent.currentTime - KMP modules (commonTest) use single-expression form.
fun foo() = runTest { … }
- 通过,且没有
./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(Turbine),绝不在flow.test { … }上直接调用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
- — canonical
androidx/testutils/testutils-ktx/src/jvmMain/kotlin/androidx/testutils/MainDispatcherRule.jvm.kt(MainDispatcherRule§G.3).docs/CORPUS.md - —
androidx/pdf/.../MainCoroutineRule.ktflavor that exposes the dispatcher.TestWatcher - —
androidx/navigationevent/...NavigationEventDispatcherTest.kt+runTest(UnconfinedTestDispatcher())pattern.launchIn(backgroundScope) - — injecting
androidx/room3/.../InvalidationTrackerTest.ktinto the SUT.TestScope().coroutineContext - Sibling: — Flow assertions,
../testing-flows-with-turbine/SKILL.md/awaitItem, hot vs cold cancellation.awaitComplete - Sibling: — mocking suspend functions with mockito-kotlin.
../../mocking/mocking-with-mockito/SKILL.md - Sibling: —
../../mocking/mocking-with-mockk/SKILL.md/coEveryfor suspend.coVerify - Sibling: — JUnit4 plumbing surrounding
../../runner/configuring-junit4-on-android/SKILL.md.runTest - Sibling: — when the SUT needs Android framework on the JVM.
../../robolectric/using-robolectric-correctly/SKILL.md - Cross-set: — small/medium/big test sizing.
../../../fundamentals/strategies/applying-testing-strategies/SKILL.md - Cross-set: — where coroutine tests belong.
../../../fundamentals/strategies/organizing-test-source-sets/SKILL.md - Cross-set: — Compose's
../../../compose/synchronization/controlling-the-test-clock/SKILL.md(separate fromMainTestClock).TestCoroutineScheduler - Cross-set: — when the same SUT runs on a device.
../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md - 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§G.3)。docs/CORPUS.md - ——公开 dispatcher 的
androidx/pdf/.../MainCoroutineRule.kt变体。TestWatcher - ——
androidx/navigationevent/...NavigationEventDispatcherTest.kt与runTest(UnconfinedTestDispatcher())模式。launchIn(backgroundScope) - ——将
androidx/room3/.../InvalidationTrackerTest.kt注入 SUT。TestScope().coroutineContext - 同级文档:——Flow 断言、
../testing-flows-with-turbine/SKILL.md/awaitItem、冷热 Flow 与取消机制。awaitComplete - 同级文档:——使用 mockito-kotlin mock suspend 函数。
../../mocking/mocking-with-mockito/SKILL.md - 同级文档:——针对 suspend 使用
../../mocking/mocking-with-mockk/SKILL.md/coEvery。coVerify - 同级文档:——围绕
../../runner/configuring-junit4-on-android/SKILL.md的 JUnit4 配置。runTest - 同级文档:——当 SUT 在 JVM 上需要 Android framework 时使用。
../../robolectric/using-robolectric-correctly/SKILL.md - 跨集合文档:——小型/中型/大型测试的规模划分。
../../../fundamentals/strategies/applying-testing-strategies/SKILL.md - 跨集合文档:——协程测试应放置的位置。
../../../fundamentals/strategies/organizing-test-source-sets/SKILL.md - 跨集合文档:——Compose 的
../../../compose/synchronization/controlling-the-test-clock/SKILL.md(独立于MainTestClock)。TestCoroutineScheduler - 跨集合文档:——当同一个 SUT 在设备上运行时使用。
../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md - 研究资料:。
tasks/research/R5-coroutines-test-turbine.md