testing-flows-with-turbine
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTesting Flows With Turbine — Assert Emissions Without toList
Hangs
toList使用 Turbine 测试 Flow——断言发射而不会因 toList
卡住
toListTurbine is the canonical way to assert emissions one-at-a-time, with built-in cancellation that prevents hot flows (, ) from hanging the test. This skill covers , the API, for multi-flow tests, and when raw actually beats Turbine. The non-Flow coroutine plumbing is .
FlowStateFlowSharedFlowflow.testReceiveTurbineturbineScopeflow.toList()../testing-coroutines-with-runtest/SKILL.mdTurbine 是逐个断言 发射的标准方式,并内置取消机制,可防止热流(、)使测试挂起。本 skill 涵盖 、 API、用于多 Flow 测试的 ,以及原始 真正优于 Turbine 的场景。非 Flow 协程相关基础设施见 。
FlowStateFlowSharedFlowflow.testReceiveTurbineturbineScopeflow.toList()../testing-coroutines-with-runtest/SKILL.mdWhen to use this skill
何时使用此 skill
- The class under test exposes a or
StateFlow<UiState>and the test must assert each emission.SharedFlow<Event> - A test hangs on over a
flow.toList()orSharedFlow— neither completes.StateFlow - The developer wants to assert "no more emissions for a beat" or "the next event is an error", which cannot express.
toList() - Two flows must be observed concurrently (e.g. plus a one-shot
uiStateflow) and asserted in interleaved order.events - The build error is or
TurbineAssertionError: Unconsumed events found.Expected an item but found Complete/Error - The developer mentions Turbine APIs: ,
awaitItem,awaitComplete,awaitError,expectMostRecentItem,skipItems,expectNoEvents,withTurbineTimeout,turbineScope.testIn
- 被测类公开 或
StateFlow<UiState>,且测试必须断言每一次发射。SharedFlow<Event> - 对 或
SharedFlow使用StateFlow时测试挂起——二者都不会完成。flow.toList() - 开发者希望断言“短时间内没有更多发射”或“下一个事件是错误”,而 无法表达这些场景。
toList() - 必须并发观察两个 Flow(例如 加一次性
uiStateFlow),并按交错顺序断言。events - 构建错误为 或
TurbineAssertionError: Unconsumed events found。Expected an item but found Complete/Error - 开发者提到 Turbine API:、
awaitItem、awaitComplete、awaitError、expectMostRecentItem、skipItems、expectNoEvents、withTurbineTimeout、turbineScope。testIn
When NOT to use this skill
何时不要使用此 skill
- The test is about ,
runTest,TestScope, or virtual time. UseDispatchers.setMainfirst; Turbine sits on top of../testing-coroutines-with-runtest/SKILL.md.runTest - The flow is cold and completes deterministically, and the assertion is "the full list equals X". is shorter — see Decision matrix below.
flow.toList() - The "flow" is actually Compose snapshot state. Read it via the test rule, not Turbine.
- 测试关注的是 、
runTest、TestScope或虚拟时间。请先使用Dispatchers.setMain;Turbine 构建在../testing-coroutines-with-runtest/SKILL.md之上。runTest - Flow 是冷流且能够确定性完成,断言目标只是“完整列表等于 X”。更简洁——参见下方决策矩阵。
flow.toList() - 所谓的“flow”实际上是 Compose snapshot state。应通过测试规则读取,而不是使用 Turbine。
Prerequisites
前置条件
- Gradle: (
testImplementation("app.cash.turbine:turbine:1.x")§G.1; R5).docs/CORPUS.md - Turbine multiplatform — JVM, Android, iOS, JS, Native, wasm. Apache 2.0, Square / Cash App.
- The surrounding test must be a body (or any
runTest { … }context).suspendis itselfflow.test { }.suspend - For multi-flow tests, because
@OptIn(ExperimentalCoroutinesApi::class)interacts withturbineScope.TestScope.backgroundScope
- Gradle:(
testImplementation("app.cash.turbine:turbine:1.x")§G.1;R5)。docs/CORPUS.md - Turbine 支持多平台——JVM、Android、iOS、JS、Native、wasm。Apache 2.0,Square / Cash App。
- 外层测试必须位于 代码块中(或任何
runTest { … }上下文中)。suspend本身是flow.test { }函数。suspend - 多 Flow 测试需要 ,因为
@OptIn(ExperimentalCoroutinesApi::class)会与turbineScope交互。TestScope.backgroundScope
flow.test signature
flow.test 签名
kotlin
public suspend fun <T> Flow<T>.test(
timeout: Duration = 3.seconds,
name: String? = null,
validate: suspend ReceiveTurbine<T>.() -> Unit,
)( §G; R5.) Three things to internalize:
docs/CORPUS.md- launches a new coroutine that calls
test { }and feeds every emission into aflow.collect { }channel. The collector is attached beforeReceiveTurbine<T>runs, so it is safe to emit into a hot flow from inside the block without dropping the first item.validate { } - The 3-second default timeout is wall clock — it is NOT driven by and does NOT honor
TestCoroutineScheduler's virtual time.runTestwaits up to 3 real seconds.awaitItem() - After returns, Turbine asserts no unconsumed events remain. If any item / completion / error is pending, it throws
validate { }. The collecting coroutine is then cancelled, so cold flows do not leak.TurbineAssertionError
The argument is appended to error messages — invaluable when multiple turbines run in one test.
namekotlin
public suspend fun <T> Flow<T>.test(
timeout: Duration = 3.seconds,
name: String? = null,
validate: suspend ReceiveTurbine<T>.() -> Unit,
)( §G;R5。)需要掌握三个要点:
docs/CORPUS.md- 会启动一个新协程来调用
test { },并将每次发射送入flow.collect { }channel。收集器会在ReceiveTurbine<T>运行前完成连接,因此即使在代码块内向热流发射,也不会丢失第一个元素。validate { } - 默认的 3 秒超时采用挂钟时间——它不由 驱动,也不遵循
TestCoroutineScheduler的虚拟时间。runTest最多等待 3 个真实秒。awaitItem() - 返回后,Turbine 会断言没有未消费的事件。如果仍有元素、完成或错误待处理,就会抛出
validate { }。随后收集协程会被取消,因此冷流不会泄漏。TurbineAssertionError
nameReceiveTurbine API
ReceiveTurbine API
kotlin
public interface ReceiveTurbine<T> {
// suspending
public suspend fun awaitItem(): T
public suspend fun awaitComplete()
public suspend fun awaitError(): Throwable
public suspend fun awaitEvent(): Event<T>
public suspend fun skipItems(count: Int)
public suspend fun cancel()
public suspend fun cancelAndIgnoreRemainingEvents()
public suspend fun cancelAndConsumeRemainingEvents(): List<Event<T>>
// non-suspending
public fun expectNoEvents()
public fun expectMostRecentItem(): T
public fun ensureAllEventsConsumed()
}(R5.)
| Call | Use when |
|---|---|
| Next event must be an item; fails on |
| Next event must be flow completion; fails on item/error. |
| Next event must be an error; returns the throwable for further assertions. |
| Sealed-class entry: |
| Drop n item events; fails if anything but an item is next. Useful to skip a |
| Non-suspending; drains buffered items and returns the latest. The "final state" assertion for |
| Non-suspending; throws if anything is buffered. Pair with |
| Stop the collector; any remaining events become an assertion failure on scope exit. |
| Stop, drain silently. The default tail of any hot-flow test. |
| Returns |
kotlin
public interface ReceiveTurbine<T> {
// suspending
public suspend fun awaitItem(): T
public suspend fun awaitComplete()
public suspend fun awaitError(): Throwable
public suspend fun awaitEvent(): Event<T>
public suspend fun skipItems(count: Int)
public suspend fun cancel()
public suspend fun cancelAndIgnoreRemainingEvents()
public suspend fun cancelAndConsumeRemainingEvents(): List<Event<T>>
// non-suspending
public fun expectNoEvents()
public fun expectMostRecentItem(): T
public fun ensureAllEventsConsumed()
}(R5。)
| 调用 | 使用场景 |
|---|---|
| 下一个事件必须是元素;如果遇到 |
| 下一个事件必须是 Flow 完成;如果遇到元素或错误则失败。 |
| 下一个事件必须是错误;返回 throwable,以便进一步断言。 |
| sealed class 条目: |
| 丢弃 n 个元素事件;如果下一个事件不是元素则失败。适用于跳过 |
| 非挂起;清空已缓冲的元素并返回最新值。适用于由 |
| 非挂起;如果存在任何已缓冲事件则抛出异常。可与 |
| 停止收集器;退出 scope 时,任何剩余事件都会导致断言失败。 |
| 停止并静默清空剩余事件。热流测试默认使用的收尾方式。 |
| 返回 |
Hot vs cold flow contract
热流与冷流契约
| Flow type | Completes naturally? | First | Need |
|---|---|---|---|
| yes | first emission | no — |
| no | next emission (or hangs) | always |
| no | seed value (replay = 1) | always |
( §G; R5.)
docs/CORPUS.mdCRITICAL: and never call . on either will hang to the 3-second wall-clock timeout. Always end with (or ).
SharedFlowStateFlowonCompletionawaitComplete()cancel()cancelAndIgnoreRemainingEvents()StateFlow.testStateFlowreplay = 1skipItems(1)| Flow 类型 | 是否自然完成? | 第一次 | 需要 |
|---|---|---|---|
| 是 | 第一次发射 | 不需要—— |
| 否 | 下一次发射(或一直挂起) | 始终需要 |
| 否 | 初始值(replay = 1) | 始终需要 |
( §G;R5。)
docs/CORPUS.md关键: 和 永远不会调用 。对二者调用 都会一直挂起,直到达到 3 秒挂钟超时。始终应以 (或 )结束。
SharedFlowStateFlowonCompletionawaitComplete()cancel()cancelAndIgnoreRemainingEvents()StateFlow.testStateFlowreplay = 1skipItems(1)turbineScope and testIn — multiple flows in one test
turbineScope 与 testIn——在一个测试中处理多个 Flow
kotlin
public suspend fun <R> turbineScope(
timeout: Duration? = null,
validate: suspend TurbineTestContext.() -> R,
): R
public fun <T> Flow<T>.testIn(
scope: CoroutineScope,
timeout: Duration? = null,
name: String? = null,
): ReceiveTurbine<T>Use these when assertions are interleaved between two flows:
kotlin
runTest(mainRule.dispatcher) {
turbineScope {
val items = repo.items.testIn(backgroundScope, name = "items")
val errors = repo.errors.testIn(backgroundScope, name = "errors")
assertEquals(0, items.awaitItem())
assertEquals(emptyList<Throwable>(), errors.expectMostRecentItem())
items.cancel()
errors.cancel()
}
}testIncancel()awaitComplete()awaitError()turbineScopekotlin
public suspend fun <R> turbineScope(
timeout: Duration? = null,
validate: suspend TurbineTestContext.() -> R,
): R
public fun <T> Flow<T>.testIn(
scope: CoroutineScope,
timeout: Duration? = null,
name: String? = null,
): ReceiveTurbine<T>当两个 Flow 的断言需要交错执行时,使用这些 API:
kotlin
runTest(mainRule.dispatcher) {
turbineScope {
val items = repo.items.testIn(backgroundScope, name = "items")
val errors = repo.errors.testIn(backgroundScope, name = "errors")
assertEquals(0, items.awaitItem())
assertEquals(emptyList<Throwable>(), errors.expectMostRecentItem())
items.cancel()
errors.cancel()
}
}在 结束前, 必须显式调用 (或 / );否则 scope 断言会抛出异常。
turbineScopetestIncancel()awaitComplete()awaitError()Standalone Turbine<T>
— capturing callbacks and one-shot signals
Turbine<T>独立的 Turbine<T>
——捕获回调和一次性信号
Turbine<T>Turbine is not only a adapter. The standalone is a send-and-receive channel with the same assertion surface — for when the thing under test is not a : a callback, a listener interface, a you own, a hand-rolled fake that needs to record invocations.
FlowTurbine<T>ReceiveTurbineFlow(T) -> UnitChannelkotlin
public fun <T> Turbine(timeout: Duration? = null, name: String? = null): Turbine<T>
public interface Turbine<T> : ReceiveTurbine<T> {
public val isClosed: Boolean
public fun add(item: T) // producer side — push an item
public fun close(cause: Throwable? = null) // signal Complete (or Error if cause != null)
public fun asChannel(): Channel<T> // hand the producer a plain SendChannel
}( §G; R5.) It turns "was this callback invoked with X, and only that?" into the same vocabulary:
docs/CORPUS.mdawaitItem()kotlin
@Test fun emitsClickedId() = runTest(mainRule.dispatcher) {
val clicks = Turbine<Long>()
val adapter = ItemAdapter(onClick = clicks::add) // production code calls onClick(id)
adapter.bind(item)
adapter.simulateClick()
assertEquals(42L, clicks.awaitItem())
clicks.ensureAllEventsConsumed() // no extra invocations slipped through
}ensureAllEventsConsumed()flow.test { }TurbineawaitComplete()close()Turbine 不只是一个 适配器。独立的 是一个具备相同 断言接口的发送与接收 channel,适用于被测对象不是 的情况: 回调、监听器接口、由你自行管理的 ,或需要记录调用情况的手写 fake。
FlowTurbine<T>ReceiveTurbineFlow(T) -> UnitChannelkotlin
public fun <T> Turbine(timeout: Duration? = null, name: String? = null): Turbine<T>
public interface Turbine<T> : ReceiveTurbine<T> {
public val isClosed: Boolean
public fun add(item: T) // producer side — push an item
public fun close(cause: Throwable? = null) // signal Complete (or Error if cause != null)
public fun asChannel(): Channel<T> // hand the producer a plain SendChannel
}( §G;R5。)它可以将“这个回调是否仅以 X 被调用”之类的断言转换为相同的 表达方式:
docs/CORPUS.mdawaitItem()kotlin
@Test fun emitsClickedId() = runTest(mainRule.dispatcher) {
val clicks = Turbine<Long>()
val adapter = ItemAdapter(onClick = clicks::add) // production code calls onClick(id)
adapter.bind(item)
adapter.simulateClick()
assertEquals(42L, clicks.awaitItem())
clicks.ensureAllEventsConsumed() // no extra invocations slipped through
}ensureAllEventsConsumed()flow.test { }Turbineclose()awaitComplete()Synchronous (non-suspend
) consumption: takeItem
/ takeComplete
/ takeError
suspendtakeItemtakeCompletetakeError同步(非 suspend
)消费:takeItem
/ takeComplete
/ takeError
suspendtakeItemtakeCompletetakeErrorWhen the assertion site cannot suspend — a plain body after the producing coroutine already ran, an inside a non- callback — exposes non-suspending takers that require the event to be buffered already and throw if it is not:
@TestassertsuspendReceiveTurbinekotlin
public fun takeItem(): T
public fun takeComplete()
public fun takeError(): Throwablekotlin
@Test fun synchronousDrain() = runTest(mainRule.dispatcher) {
val turbine = vm.uiState.testIn(backgroundScope)
advanceUntilIdle() // let the producer run to quiescence (virtual time)
assertEquals(Idle, turbine.takeItem()) // no suspension — the value is already buffered
assertEquals(Loaded, turbine.takeItem())
turbine.cancel()
}Prefer suspending inside / blocks; reach for only when the call site genuinely cannot suspend.
awaitItem()runTestflow.testtakeItem()当断言位置无法挂起时——例如生产协程已经运行后的普通 代码块,或非 回调内部的 —— 提供非挂起式获取方法。这些方法要求事件已经被缓冲,否则会抛出异常:
@TestsuspendassertReceiveTurbinekotlin
public fun takeItem(): T
public fun takeComplete()
public fun takeError(): Throwablekotlin
@Test fun synchronousDrain() = runTest(mainRule.dispatcher) {
val turbine = vm.uiState.testIn(backgroundScope)
advanceUntilIdle() // let the producer run to quiescence (virtual time)
assertEquals(Idle, turbine.takeItem()) // no suspension — the value is already buffered
assertEquals(Loaded, turbine.takeItem())
turbine.cancel()
}在 / 代码块中,优先使用挂起式 ;仅当调用位置确实无法挂起时,才使用 。
runTestflow.testawaitItem()takeItem()Turbine timeout vs runTest virtual time
Turbine 超时与 runTest 虚拟时间
Turbine's 3-second default is wall clock, never virtual. 's 60-second default is also wall clock — but inside the test body manipulates virtual time, which Turbine does not see.
runTestadvanceTimeBy(...)TestCoroutineSchedulerImplication: a test using finishes in microseconds because skips the delay. But a that waits for an emission whose source is real network I/O still observes real wall-clock time. If the wait is genuinely longer than 3 seconds in real time, override:
delay(10.minutes)runTestflow.test { awaitItem() }kotlin
flow.test(timeout = 10.seconds) { … } // per-call
withTurbineTimeout(10.seconds) { // scoped
flow.test { … }
}Turbine 默认的 3 秒采用挂钟时间,绝不会是虚拟时间。 默认的 60 秒同样是挂钟时间——但测试代码中的 会操作 的虚拟时间,而 Turbine 无法感知该时间。
runTestadvanceTimeBy(...)TestCoroutineScheduler影响如下:使用 的测试只需几微秒即可完成,因为 会跳过该延迟。但等待真实网络 I/O 发射的 仍按真实挂钟时间计时。如果实际等待时间确实超过 3 秒,请覆盖超时:
delay(10.minutes)runTestflow.test { awaitItem() }kotlin
flow.test(timeout = 10.seconds) { … } // per-call
withTurbineTimeout(10.seconds) { // scoped
flow.test { … }
}Decision matrix — Turbine vs raw flow.toList()
flow.toList()决策矩阵——Turbine 与原始 flow.toList()
flow.toList()| Scenario | Pick |
|---|---|
| Cold flow that completes; "the full list equals X" | |
Hot | Turbine (handles cancellation) |
| Need to assert intermediate state then trigger more emissions | Turbine |
| Need to assert "no more events for a while" | Turbine ( |
| Need to assert error type / completion | Turbine ( |
| Multiple flows interleaved in one test | Turbine ( |
| Multiplatform test on JS/Native | Both work; Turbine is easier |
| Zero extra dependency | |
(R5.)
Rule of thumb: prefer Turbine for any UI-state / ViewModel test (almost always -driven), and for repository/transformation tests of cold flows that complete deterministically.
StateFlowflow.toList()| 场景 | 选择 |
|---|---|
| 能够完成的冷流;“完整列表等于 X” | |
热 | Turbine(可正确处理取消) |
| 需要先断言中间状态,再触发更多发射 | Turbine |
| 需要断言“一段时间内没有更多事件” | Turbine( |
| 需要断言错误类型或完成状态 | Turbine( |
| 在一个测试中交错处理多个 Flow | Turbine( |
| 在 JS/Native 上进行多平台测试 | 两者都可用;Turbine 更简单 |
| 不增加任何额外依赖 | |
(R5。)
经验法则:对于任何 UI state / ViewModel 测试,几乎都应优先使用 Turbine(通常由 驱动);对于能够确定性完成的冷流 repository/转换测试,应使用 。
StateFlowflow.toList()Patterns
模式
Pattern: WRONG — flow.toList()
on a SharedFlow
flow.toList()模式:错误——对 SharedFlow 使用 flow.toList()
flow.toList()kotlin
// WRONG
@Test fun events() = runTest {
val events: SharedFlow<Event> = vm.events
val collected = events.toList() // never returns
assertEquals(listOf(LoggedIn), collected)
}
// WRONG because: SharedFlow never completes. toList() suspends until the upstream
// completes, which it never does. The test hangs to the 60s runTest timeout.kotlin
// RIGHT
@Test fun events() = runTest(mainRule.dispatcher) {
vm.events.test {
vm.login()
assertEquals(LoggedIn, awaitItem())
cancelAndIgnoreRemainingEvents() // hot flow — must cancel
}
}kotlin
// WRONG
@Test fun events() = runTest {
val events: SharedFlow<Event> = vm.events
val collected = events.toList() // never returns
assertEquals(listOf(LoggedIn), collected)
}
// WRONG because: SharedFlow never completes. toList() suspends until the upstream
// completes, which it never does. The test hangs to the 60s runTest timeout.kotlin
// RIGHT
@Test fun events() = runTest(mainRule.dispatcher) {
vm.events.test {
vm.login()
assertEquals(LoggedIn, awaitItem())
cancelAndIgnoreRemainingEvents() // hot flow — must cancel
}
}Pattern: WRONG — forgetting StateFlow's seed value
模式:错误——忘记 StateFlow 的初始值
kotlin
// WRONG
@Test fun stateFlowEmits() = runTest(mainRule.dispatcher) {
vm.uiState.test {
vm.refresh()
assertEquals(Loading, awaitItem()) // FAIL: actually Idle (seed)
cancel()
}
}
// WRONG because: StateFlow has replay = 1. The collector immediately receives the
// current value (Idle) before any new emission. The first awaitItem() returns
// the seed, not the post-refresh state.kotlin
// RIGHT — assert the seed
@Test fun stateFlowEmits() = runTest(mainRule.dispatcher) {
vm.uiState.test {
assertEquals(Idle, awaitItem()) // seed
vm.refresh()
assertEquals(Loading, awaitItem())
assertEquals(Success(items), awaitItem())
cancelAndIgnoreRemainingEvents()
}
}
// RIGHT — skip the seed if you do not care
@Test fun stateFlowEmits_skipSeed() = runTest(mainRule.dispatcher) {
vm.uiState.test {
skipItems(1)
vm.refresh()
assertEquals(Loading, awaitItem())
assertEquals(Success(items), awaitItem())
cancelAndIgnoreRemainingEvents()
}
}kotlin
// WRONG
@Test fun stateFlowEmits() = runTest(mainRule.dispatcher) {
vm.uiState.test {
vm.refresh()
assertEquals(Loading, awaitItem()) // FAIL: actually Idle (seed)
cancel()
}
}
// WRONG because: StateFlow has replay = 1. The collector immediately receives the
// current value (Idle) before any new emission. The first awaitItem() returns
// the seed, not the post-refresh state.kotlin
// RIGHT — assert the seed
@Test fun stateFlowEmits() = runTest(mainRule.dispatcher) {
vm.uiState.test {
assertEquals(Idle, awaitItem()) // seed
vm.refresh()
assertEquals(Loading, awaitItem())
assertEquals(Success(items), awaitItem())
cancelAndIgnoreRemainingEvents()
}
}
// RIGHT — skip the seed if you do not care
@Test fun stateFlowEmits_skipSeed() = runTest(mainRule.dispatcher) {
vm.uiState.test {
skipItems(1)
vm.refresh()
assertEquals(Loading, awaitItem())
assertEquals(Success(items), awaitItem())
cancelAndIgnoreRemainingEvents()
}
}Pattern: WRONG — awaitComplete()
on a hot flow
awaitComplete()模式:错误——在热流上调用 awaitComplete()
awaitComplete()kotlin
// WRONG
@Test fun events() = runTest {
vm.events.test {
vm.login()
assertEquals(LoggedIn, awaitItem())
awaitComplete() // hangs 3s, then TurbineAssertionError
}
}
// WRONG because: SharedFlow never completes. awaitComplete() waits 3 wall-clock
// seconds (Turbine default) and then throws. The test is slow AND fails.kotlin
// RIGHT
@Test fun events() = runTest(mainRule.dispatcher) {
vm.events.test {
vm.login()
assertEquals(LoggedIn, awaitItem())
cancelAndIgnoreRemainingEvents()
}
}kotlin
// WRONG
@Test fun events() = runTest {
vm.events.test {
vm.login()
assertEquals(LoggedIn, awaitItem())
awaitComplete() // hangs 3s, then TurbineAssertionError
}
}
// WRONG because: SharedFlow never completes. awaitComplete() waits 3 wall-clock
// seconds (Turbine default) and then throws. The test is slow AND fails.kotlin
// RIGHT
@Test fun events() = runTest(mainRule.dispatcher) {
vm.events.test {
vm.login()
assertEquals(LoggedIn, awaitItem())
cancelAndIgnoreRemainingEvents()
}
}Pattern: conflated StateFlow — use expectMostRecentItem
expectMostRecentItem模式:合并的 StateFlow——使用 expectMostRecentItem
expectMostRecentItemkotlin
@Test fun finalState() = runTest(mainRule.dispatcher) {
vm.uiState.test {
skipItems(1) // seed
vm.flipFast() // posts 5 transitions in <1ms
advanceUntilIdle() // virtual; let coroutines settle
// StateFlow conflates — only the latest value is kept.
// awaitItem() may see anything from the burst; expectMostRecentItem is deterministic.
assertEquals(Final, expectMostRecentItem())
cancelAndIgnoreRemainingEvents()
}
}kotlin
@Test fun finalState() = runTest(mainRule.dispatcher) {
vm.uiState.test {
skipItems(1) // seed
vm.flipFast() // posts 5 transitions in <1ms
advanceUntilIdle() // virtual; let coroutines settle
// StateFlow conflates — only the latest value is kept.
// awaitItem() may see anything from the burst; expectMostRecentItem is deterministic.
assertEquals(Final, expectMostRecentItem())
cancelAndIgnoreRemainingEvents()
}
}Pattern: assert "no more events"
模式:断言“没有更多事件”
kotlin
@Test fun noSpuriousEmissions() = runTest(mainRule.dispatcher) {
vm.uiState.test {
skipItems(1)
vm.refresh()
assertEquals(Loading, awaitItem())
assertEquals(Success(items), awaitItem())
advanceTimeBy(5.seconds) // virtual — flush any timers
runCurrent()
expectNoEvents() // confirms quiescence
cancelAndIgnoreRemainingEvents()
}
}kotlin
@Test fun noSpuriousEmissions() = runTest(mainRule.dispatcher) {
vm.uiState.test {
skipItems(1)
vm.refresh()
assertEquals(Loading, awaitItem())
assertEquals(Success(items), awaitItem())
advanceTimeBy(5.seconds) // virtual — flush any timers
runCurrent()
expectNoEvents() // confirms quiescence
cancelAndIgnoreRemainingEvents()
}
}Pattern: cold flow that completes — Turbine vs toList
模式:能够完成的冷流——Turbine 与 toList
kotlin
// FINE — toList() is shorter for terminal cold flows
@Test fun coldList() = runTest {
val collected = flowOf(1, 2, 3).toList()
assertEquals(listOf(1, 2, 3), collected)
}
// ALSO FINE — Turbine if you need intermediate-state assertions
@Test fun coldTurbine() = runTest {
flowOf(1, 2, 3).test {
assertEquals(1, awaitItem())
assertEquals(2, awaitItem())
assertEquals(3, awaitItem())
awaitComplete() // cold flow — completes naturally
}
}kotlin
// FINE — toList() is shorter for terminal cold flows
@Test fun coldList() = runTest {
val collected = flowOf(1, 2, 3).toList()
assertEquals(listOf(1, 2, 3), collected)
}
// ALSO FINE — Turbine if you need intermediate-state assertions
@Test fun coldTurbine() = runTest {
flowOf(1, 2, 3).test {
assertEquals(1, awaitItem())
assertEquals(2, awaitItem())
assertEquals(3, awaitItem())
awaitComplete() // cold flow — completes naturally
}
}Pattern: two flows interleaved with turbineScope
turbineScope模式:使用 turbineScope
交错处理两个 Flow
turbineScopekotlin
@Test fun interleaved() = runTest(mainRule.dispatcher) {
turbineScope {
val state = vm.uiState.testIn(backgroundScope, name = "state")
val events = vm.events.testIn(backgroundScope, name = "events")
assertEquals(Idle, state.awaitItem())
vm.login()
assertEquals(Loading, state.awaitItem())
assertEquals(LoggedIn, events.awaitItem())
assertEquals(Success, state.awaitItem())
state.cancel(); events.cancel()
}
}kotlin
@Test fun interleaved() = runTest(mainRule.dispatcher) {
turbineScope {
val state = vm.uiState.testIn(backgroundScope, name = "state")
val events = vm.events.testIn(backgroundScope, name = "events")
assertEquals(Idle, state.awaitItem())
vm.login()
assertEquals(Loading, state.awaitItem())
assertEquals(LoggedIn, events.awaitItem())
assertEquals(Success, state.awaitItem())
state.cancel(); events.cancel()
}
}Mandatory rules
强制规则
- MUST wrap any /
StateFlowassertion inSharedFlow. MUST NOT callflow.test { … cancelAndIgnoreRemainingEvents() }on a hot flow — the test hangs.flow.toList() - MUST call /
cancel()at the end of everycancelAndIgnoreRemainingEvents()block over a hot flow.test { }is wrong for hot flows — they never complete.awaitComplete() - MUST account for 's seed value: the first
StateFlowreturns the current value (replay = 1). Either assert it orawaitItem().skipItems(1) - MUST depend on Turbine from only. MUST NOT put
testImplementationonapp.cash.turbine.implementation - MUST override (or per-call
withTurbineTimeout(...)) when the awaited emission genuinely takes more than 3 wall-clock seconds. The 3 s default is wall clock and is independent fromtimeout =virtual time.runTest - MUST use (NOT
cancel()) insideawaitComplete()blocks beforetestInends; otherwise the scope assertion throws.turbineScope - MUST NOT mix Turbine timeouts with 's virtual clock semantics.
runTestis virtual; Turbine's 3-second wait is real.advanceTimeBy(10.minutes) - PREFERRED: for deterministic "final state" assertions on conflated
expectMostRecentItem()where intermediate values may be collapsed.StateFlow - PREFERRED: raw for cold flows that complete deterministically — Turbine is overhead in that case.
flow.toList() - PREFERRED: name turbines (,
flow.test(name = "uiState")) when more than one runs in a test — error messages cite the name.flow.testIn(scope, name = "events") - PREFERRED: the standalone (with
Turbine<T>()/add/close) over a manually accumulatedensureAllEventsConsumedwhen verifying aMutableListcallback or a listener was invoked — it gives the same(T) -> Unitdiagnostics and the unconsumed-event check.awaitItem() - PREFERRED: suspending inside
awaitItem()/runTestblocks over the non-suspendingflow.test/takeItem()/takeComplete(); reach for the takers only when the call site genuinely cannot suspend.takeError()
- 必须将所有 /
StateFlow断言包裹在SharedFlow中。不得对热流调用flow.test { … cancelAndIgnoreRemainingEvents() }——测试会挂起。flow.toList() - 必须在每个针对热流的 代码块末尾调用
test { }/cancel()。热流永不完成,因此调用cancelAndIgnoreRemainingEvents()是错误的。awaitComplete() - 必须处理 的初始值:第一次
StateFlow返回当前值(replay = 1)。应断言该值,或在继续断言前调用awaitItem()。skipItems(1) - 必须仅通过 依赖 Turbine。不得将
testImplementation放在app.cash.turbine中。implementation - 如果所等待的发射确实需要超过 3 个挂钟秒,必须覆盖 (或单次调用的
withTurbineTimeout(...))。默认的 3 秒采用挂钟时间,与timeout =虚拟时间相互独立。runTest - 必须在 结束前,于
turbineScope代码块内调用testIn(而不是cancel());否则 scope 断言会抛出异常。awaitComplete() - 不得混用 Turbine 超时与 的虚拟时钟语义。
runTest使用虚拟时间;Turbine 的 3 秒等待使用真实时间。advanceTimeBy(10.minutes) - **推荐:**对于会合并中间值的 ,当需要确定性的“最终状态”断言时,使用
StateFlow。expectMostRecentItem() - **推荐:**对于能够确定性完成的冷流,使用原始 ——此时 Turbine 属于额外开销。
flow.toList() - **推荐:**当一个测试中运行多个 Turbine 时为其命名(、
flow.test(name = "uiState"))——错误消息会引用该名称。flow.testIn(scope, name = "events") - **推荐:**验证 回调或监听器是否被调用时,使用独立的
(T) -> Unit(配合Turbine<T>()/add/close),而不是手动累积ensureAllEventsConsumed——它能提供相同的MutableList诊断信息和未消费事件检查。awaitItem() - **推荐:**在 /
runTest代码块中使用挂起式flow.test,而不是非挂起式awaitItem()/takeItem()/takeComplete();仅当调用位置确实无法挂起时才使用这些获取方法。takeError()
Verification
验证
- No call exists on any
flow.toList()orStateFlow(SharedFlowcross-checked against flow types).grep -rn 'toList()' src/test - Every over a hot flow ends with
flow.test { … }orcancel().cancelAndIgnoreRemainingEvents() - No is called on a
awaitComplete()/StateFlow.SharedFlow - tests either assert the seed via
StateFloworawaitItem()before further assertions.skipItems(1) - Turbines that may legitimately wait > 3 s use or per-call
withTurbineTimeout(...).timeout = N.seconds - Multi-flow tests use rather than nested
turbineScope { … testIn(backgroundScope) … }blocks.test { } - Callback / listener assertions use a standalone (with
Turbine<T>()), not an ad-hocensureAllEventsConsumed().MutableList - CI run completes 50 iterations without flakes.
TurbineAssertionError
- 任何 或
StateFlow上都不存在SharedFlow调用(通过flow.toList()交叉检查 Flow 类型)。grep -rn 'toList()' src/test - 每个针对热流的 都以
flow.test { … }或cancel()结束。cancelAndIgnoreRemainingEvents() - 不对 /
StateFlow调用SharedFlow。awaitComplete() - 测试会通过
StateFlow断言初始值,或在继续断言前调用awaitItem()。skipItems(1) - 可能合法等待超过 3 秒的 Turbine 使用 或单次调用
withTurbineTimeout(...)。timeout = N.seconds - 多 Flow 测试使用 ,而不是嵌套的
turbineScope { … testIn(backgroundScope) … }代码块。test { } - 回调 / 监听器断言使用独立的 (并调用
Turbine<T>()),而不是临时编写的ensureAllEventsConsumed()。MutableList - CI 运行 50 次后仍能完成,且不会出现 flaky failure。
TurbineAssertionError
References
参考资料
- Cash App Turbine — README and API: https://github.com/cashapp/turbine
- Cash App Turbine — releases: https://github.com/cashapp/turbine/releases
- Android Developers — Test Kotlin Flow on Android: https://developer.android.com/kotlin/flow/test
- Android Developers — StateFlow & SharedFlow: https://developer.android.com/kotlin/flow/stateflow-and-sharedflow
- JetBrains — Asynchronous Flow: https://kotlinlang.org/docs/flow.html
- Research: — Turbine API surface, hot/cold contract, comparison with
tasks/research/R5-coroutines-test-turbine.md.toList() - §G.1 — Gradle coordinates and version pin.
docs/CORPUS.md - Sibling: —
../testing-coroutines-with-runtest/SKILL.md,runTest, virtual time foundations Turbine sits on top of.MainDispatcherRule - Sibling: — mocking suspend dependencies that produce flows.
../../mocking/mocking-with-mockito/SKILL.md - Sibling: —
../../mocking/mocking-with-mockk/SKILL.md.coEvery { repo.items() } returns flowOf(...) - Sibling: — JUnit4 plumbing.
../../runner/configuring-junit4-on-android/SKILL.md - Sibling: — when the SUT needs Android framework on the JVM.
../../robolectric/using-robolectric-correctly/SKILL.md - Cross-set: — small/medium/big sizing for Flow tests.
../../../fundamentals/strategies/applying-testing-strategies/SKILL.md - Cross-set: — where Flow tests belong (
../../../fundamentals/strategies/organizing-test-source-sets/SKILL.md).src/test/ - Cross-set: — Compose's
../../../compose/synchronization/controlling-the-test-clock/SKILL.mdis independent of Turbine's wall clock.MainTestClock - Cross-set: — Turbine works on-device too, with the same API.
../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md - Cross-set: —
../../../kotlin/kotlin-test/writing-tests-with-kotlin-test/SKILL.mdpaired withawaitItem()'skotlin.test/assertEquals; the assertion vocabulary insideassertIs.flow.test { }
- Cash App Turbine——README 与 API:https://github.com/cashapp/turbine
- Cash App Turbine——发布版本:https://github.com/cashapp/turbine/releases
- Android Developers——在 Android 上测试 Kotlin Flow:https://developer.android.com/kotlin/flow/test
- Android Developers——StateFlow 与 SharedFlow:https://developer.android.com/kotlin/flow/stateflow-and-sharedflow
- JetBrains——异步 Flow:https://kotlinlang.org/docs/flow.html
- Research:——Turbine API、热流/冷流契约,以及与
tasks/research/R5-coroutines-test-turbine.md的比较。toList() - §G.1——Gradle 坐标与版本固定。
docs/CORPUS.md - Sibling:——Turbine 所基于的
../testing-coroutines-with-runtest/SKILL.md、runTest和虚拟时间基础。MainDispatcherRule - Sibling:——模拟会产生 Flow 的 suspend 依赖项。
../../mocking/mocking-with-mockito/SKILL.md - Sibling:——
../../mocking/mocking-with-mockk/SKILL.md。coEvery { repo.items() } returns flowOf(...) - Sibling:——JUnit4 基础设施。
../../runner/configuring-junit4-on-android/SKILL.md - Sibling:——当 SUT 在 JVM 上需要 Android framework 时使用。
../../robolectric/using-robolectric-correctly/SKILL.md - Cross-set:——为 Flow 测试选择小型/中型/大型测试规模。
../../../fundamentals/strategies/applying-testing-strategies/SKILL.md - Cross-set:——Flow 测试的存放位置(
../../../fundamentals/strategies/organizing-test-source-sets/SKILL.md)。src/test/ - Cross-set:——Compose 的
../../../compose/synchronization/controlling-the-test-clock/SKILL.md独立于 Turbine 的挂钟时间。MainTestClock - Cross-set:——Turbine 也可在设备上使用,并提供相同的 API。
../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md - Cross-set:——将
../../../kotlin/kotlin-test/writing-tests-with-kotlin-test/SKILL.md与awaitItem()的kotlin.test/assertEquals配合使用;这是assertIs内部的断言表达方式。flow.test { }