testing-flows-with-turbine

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Testing Flows With Turbine — Assert Emissions Without
toList
Hangs

使用 Turbine 测试 Flow——断言发射而不会因
toList
卡住

Turbine is the canonical way to assert
Flow
emissions one-at-a-time, with built-in cancellation that prevents hot flows (
StateFlow
,
SharedFlow
) from hanging the test. This skill covers
flow.test
, the
ReceiveTurbine
API,
turbineScope
for multi-flow tests, and when raw
flow.toList()
actually beats Turbine. The non-Flow coroutine plumbing is
../testing-coroutines-with-runtest/SKILL.md
.
Turbine 是逐个断言
Flow
发射的标准方式,并内置取消机制,可防止热流(
StateFlow
、
SharedFlow
)使测试挂起。本 skill 涵盖
flow.test
、
ReceiveTurbine
API、用于多 Flow 测试的
turbineScope
,以及原始
flow.toList()
真正优于 Turbine 的场景。非 Flow 协程相关基础设施见
../testing-coroutines-with-runtest/SKILL.md
。

When to use this skill

何时使用此 skill

  • The class under test exposes a
    StateFlow<UiState>
    or
    SharedFlow<Event>
    and the test must assert each emission.
  • A test hangs on
    flow.toList()
    over a
    SharedFlow
    or
    StateFlow
    — neither completes.
  • The developer wants to assert "no more emissions for a beat" or "the next event is an error", which
    toList()
    cannot express.
  • Two flows must be observed concurrently (e.g.
    uiState
    plus a one-shot
    events
    flow) and asserted in interleaved order.
  • The build error is
    TurbineAssertionError: Unconsumed events found
    or
    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(例如
    uiState
    加一次性
    events
    Flow),并按交错顺序断言。
  • 构建错误为
    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
    ,
    Dispatchers.setMain
    , or virtual time. Use
    ../testing-coroutines-with-runtest/SKILL.md
    first; Turbine sits on top of
    runTest
    .
  • The flow is cold and completes deterministically, and the assertion is "the full list equals X".
    flow.toList()
    is shorter — see Decision matrix below.
  • The "flow" is actually Compose snapshot state. Read it via the test rule, not Turbine.
  • 测试关注的是
    runTest
    、
    TestScope
    、
    Dispatchers.setMain
    或虚拟时间。请先使用
    ../testing-coroutines-with-runtest/SKILL.md
    ;Turbine 构建在
    runTest
    之上。
  • Flow 是冷流且能够确定性完成,断言目标只是“完整列表等于 X”。
    flow.toList()
    更简洁——参见下方决策矩阵。
  • 所谓的“flow”实际上是 Compose snapshot state。应通过测试规则读取,而不是使用 Turbine。

Prerequisites

前置条件

  • Gradle:
    testImplementation("app.cash.turbine:turbine:1.x")
    (
    docs/CORPUS.md
    §G.1; R5).
  • Turbine multiplatform — JVM, Android, iOS, JS, Native, wasm. Apache 2.0, Square / Cash App.
  • The surrounding test must be a
    runTest { … }
    body (or any
    suspend
    context).
    flow.test { }
    is itself
    suspend
    .
  • For multi-flow tests,
    @OptIn(ExperimentalCoroutinesApi::class)
    because
    turbineScope
    interacts with
    TestScope.backgroundScope
    .
  • Gradle:
    testImplementation("app.cash.turbine:turbine:1.x")
    (
    docs/CORPUS.md
    §G.1;R5)。
  • 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,
)
(
docs/CORPUS.md
§G; R5.) Three things to internalize:
  1. test { }
    launches a new coroutine that calls
    flow.collect { }
    and feeds every emission into a
    ReceiveTurbine<T>
    channel. The collector is attached before
    validate { }
    runs, so it is safe to emit into a hot flow from inside the block without dropping the first item.
  2. The 3-second default timeout is wall clock — it is NOT driven by
    TestCoroutineScheduler
    and does NOT honor
    runTest
    's virtual time.
    awaitItem()
    waits up to 3 real seconds.
  3. After
    validate { }
    returns, Turbine asserts no unconsumed events remain. If any item / completion / error is pending, it throws
    TurbineAssertionError
    . The collecting coroutine is then cancelled, so cold flows do not leak.
The
name
argument is appended to error messages — invaluable when multiple turbines run in one test.
kotlin
public suspend fun <T> Flow<T>.test(
    timeout: Duration = 3.seconds,
    name: String? = null,
    validate: suspend ReceiveTurbine<T>.() -> Unit,
)
(
docs/CORPUS.md
§G;R5。)需要掌握三个要点:
  1. test { }
    会启动一个新协程来调用
    flow.collect { }
    ,并将每次发射送入
    ReceiveTurbine<T>
    channel。收集器会在
    validate { }
    运行前完成连接,因此即使在代码块内向热流发射,也不会丢失第一个元素。
  2. 默认的 3 秒超时采用挂钟时间——它不由
    TestCoroutineScheduler
    驱动,也不遵循
    runTest
    的虚拟时间。
    awaitItem()
    最多等待 3 个真实秒。
  3. validate { }
    返回后,Turbine 会断言没有未消费的事件。如果仍有元素、完成或错误待处理,就会抛出
    TurbineAssertionError
    。随后收集协程会被取消,因此冷流不会泄漏。
name
参数会附加到错误消息中——当一个测试中运行多个 Turbine 时,这一点非常有用。

ReceiveTurbine 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.)
CallUse when
awaitItem(): T
Next event must be an item; fails on
Complete
/
Error
.
awaitComplete()
Next event must be flow completion; fails on item/error.
awaitError(): Throwable
Next event must be an error; returns the throwable for further assertions.
awaitEvent(): Event<T>
Sealed-class entry:
Event.Item(value)
,
Event.Complete
,
Event.Error(throwable)
.
skipItems(n)
Drop n item events; fails if anything but an item is next. Useful to skip a
StateFlow
's seed.
expectMostRecentItem()
Non-suspending; drains buffered items and returns the latest. The "final state" assertion for
StateFlow
-driven UIs where intermediate values are lossy.
expectNoEvents()
Non-suspending; throws if anything is buffered. Pair with
runCurrent()
/
advanceTimeBy(...)
to assert no spurious emissions.
cancel()
Stop the collector; any remaining events become an assertion failure on scope exit.
cancelAndIgnoreRemainingEvents()
Stop, drain silently. The default tail of any hot-flow test.
cancelAndConsumeRemainingEvents()
Returns
List<Event<T>>
for ad-hoc inspection.
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。)
调用使用场景
awaitItem(): T
下一个事件必须是元素;如果遇到
Complete
/
Error
则失败。
awaitComplete()
下一个事件必须是 Flow 完成;如果遇到元素或错误则失败。
awaitError(): Throwable
下一个事件必须是错误;返回 throwable,以便进一步断言。
awaitEvent(): Event<T>
sealed class 条目:
Event.Item(value)
、
Event.Complete
、
Event.Error(throwable)
。
skipItems(n)
丢弃 n 个元素事件;如果下一个事件不是元素则失败。适用于跳过
StateFlow
的初始值。
expectMostRecentItem()
非挂起;清空已缓冲的元素并返回最新值。适用于由
StateFlow
驱动的 UI,其中间值可能会丢失。
expectNoEvents()
非挂起;如果存在任何已缓冲事件则抛出异常。可与
runCurrent()
/
advanceTimeBy(...)
配合,用于断言没有意外发射。
cancel()
停止收集器;退出 scope 时,任何剩余事件都会导致断言失败。
cancelAndIgnoreRemainingEvents()
停止并静默清空剩余事件。热流测试默认使用的收尾方式。
cancelAndConsumeRemainingEvents()
返回
List<Event<T>>
,便于临时检查。

Hot vs cold flow contract

热流与冷流契约

Flow typeCompletes naturally?First
awaitItem()
returns
Need
cancel()
?
flowOf(...)
/
flow { }
(cold)
yesfirst emissionno —
awaitComplete()
terminates
MutableSharedFlow<T>
(replay = 0)
nonext emission (or hangs)always
MutableStateFlow<T>
noseed value (replay = 1)always
(
docs/CORPUS.md
§G; R5.)
CRITICAL:
SharedFlow
and
StateFlow
never call
onCompletion
.
awaitComplete()
on either will hang to the 3-second wall-clock timeout. Always end with
cancel()
(or
cancelAndIgnoreRemainingEvents()
).
StateFlow.test
always emits the seed value first because
StateFlow
has
replay = 1
. If you do not care about the seed,
skipItems(1)
it.
Flow 类型是否自然完成?第一次
awaitItem()
返回
需要
cancel()
?
flowOf(...)
/
flow { }
(冷流)
是第一次发射不需要——
awaitComplete()
会终止
MutableSharedFlow<T>
(replay = 0)
否下一次发射(或一直挂起)始终需要
MutableStateFlow<T>
否初始值(replay = 1)始终需要
(
docs/CORPUS.md
§G;R5。)
关键:
SharedFlow
和
StateFlow
永远不会调用
onCompletion
。对二者调用
awaitComplete()
都会一直挂起,直到达到 3 秒挂钟超时。始终应以
cancel()
(或
cancelAndIgnoreRemainingEvents()
)结束。
StateFlow.test
总是先发射初始值,因为
StateFlow
的
replay = 1
。如果不关心该初始值,可以使用
skipItems(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()
    }
}
testIn
requires explicit
cancel()
(or
awaitComplete()
/
awaitError()
) before the
turbineScope
ends; otherwise the scope assertion throws.
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>
当两个 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()
    }
}
在
turbineScope
结束前,
testIn
必须显式调用
cancel()
(或
awaitComplete()
/
awaitError()
);否则 scope 断言会抛出异常。

Standalone
Turbine<T>
— capturing callbacks and one-shot signals

独立的
Turbine<T>
——捕获回调和一次性信号

Turbine is not only a
Flow
adapter. The standalone
Turbine<T>
is a send-and-receive channel with the same
ReceiveTurbine
assertion surface — for when the thing under test is not a
Flow
: a
(T) -> Unit
callback, a listener interface, a
Channel
you own, a hand-rolled fake that needs to record invocations.
kotlin
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
}
(
docs/CORPUS.md
§G; R5.) It turns "was this callback invoked with X, and only that?" into the same
awaitItem()
vocabulary:
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()
asserts nothing is left buffered — the standalone-Turbine equivalent of the check
flow.test { }
runs implicitly on block exit. A standalone
Turbine
never auto-completes, so
awaitComplete()
on one hangs to the timeout unless you
close()
it; treat it like a hot flow.
Turbine 不只是一个
Flow
适配器。独立的
Turbine<T>
是一个具备相同
ReceiveTurbine
断言接口的发送与接收 channel,适用于被测对象不是
Flow
的情况:
(T) -> Unit
回调、监听器接口、由你自行管理的
Channel
,或需要记录调用情况的手写 fake。
kotlin
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
}
(
docs/CORPUS.md
§G;R5。)它可以将“这个回调是否仅以 X 被调用”之类的断言转换为相同的
awaitItem()
表达方式:
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()
会断言没有遗留的已缓冲事件,相当于独立 Turbine 中对
flow.test { }
退出时隐式检查的显式版本。独立的
Turbine
永不自动完成,因此除非调用
close()
,否则对它调用
awaitComplete()
会一直挂起至超时;应将其视为热流。

Synchronous (non-
suspend
) consumption:
takeItem
/
takeComplete
/
takeError

同步(非
suspend
)消费:
takeItem
/
takeComplete
/
takeError

When the assertion site cannot suspend — a plain
@Test
body after the producing coroutine already ran, an
assert
inside a non-
suspend
callback —
ReceiveTurbine
exposes non-suspending takers that require the event to be buffered already and throw if it is not:
kotlin
public fun takeItem(): T
public fun takeComplete()
public fun takeError(): Throwable
kotlin
@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
awaitItem()
inside
runTest
/
flow.test
blocks; reach for
takeItem()
only when the call site genuinely cannot suspend.
当断言位置无法挂起时——例如生产协程已经运行后的普通
@Test
代码块,或非
suspend
回调内部的
assert
——
ReceiveTurbine
提供非挂起式获取方法。这些方法要求事件已经被缓冲,否则会抛出异常:
kotlin
public fun takeItem(): T
public fun takeComplete()
public fun takeError(): Throwable
kotlin
@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()
}
在
runTest
/
flow.test
代码块中,优先使用挂起式
awaitItem()
;仅当调用位置确实无法挂起时,才使用
takeItem()
。

Turbine timeout vs runTest virtual time

Turbine 超时与 runTest 虚拟时间

Turbine's 3-second default is wall clock, never virtual.
runTest
's 60-second default is also wall clock — but
advanceTimeBy(...)
inside the test body manipulates
TestCoroutineScheduler
virtual time, which Turbine does not see.
Implication: a test using
delay(10.minutes)
finishes in microseconds because
runTest
skips the delay. But a
flow.test { awaitItem() }
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:
kotlin
flow.test(timeout = 10.seconds) { … }            // per-call

withTurbineTimeout(10.seconds) {                 // scoped
    flow.test { … }
}
Turbine 默认的 3 秒采用挂钟时间,绝不会是虚拟时间。
runTest
默认的 60 秒同样是挂钟时间——但测试代码中的
advanceTimeBy(...)
会操作
TestCoroutineScheduler
的虚拟时间,而 Turbine 无法感知该时间。
影响如下:使用
delay(10.minutes)
的测试只需几微秒即可完成,因为
runTest
会跳过该延迟。但等待真实网络 I/O 发射的
flow.test { awaitItem() }
仍按真实挂钟时间计时。如果实际等待时间确实超过 3 秒,请覆盖超时:
kotlin
flow.test(timeout = 10.seconds) { … }            // per-call

withTurbineTimeout(10.seconds) {                 // scoped
    flow.test { … }
}

Decision matrix — Turbine vs raw
flow.toList()

决策矩阵——Turbine 与原始
flow.toList()

ScenarioPick
Cold flow that completes; "the full list equals X"
flow.toList()
(shorter)
Hot
StateFlow
/
SharedFlow
Turbine (handles cancellation)
Need to assert intermediate state then trigger more emissionsTurbine
Need to assert "no more events for a while"Turbine (
expectNoEvents
)
Need to assert error type / completionTurbine (
awaitError
,
awaitComplete
)
Multiple flows interleaved in one testTurbine (
turbineScope
/
testIn
)
Multiplatform test on JS/NativeBoth work; Turbine is easier
Zero extra dependency
flow.toList()
(R5.)
Rule of thumb: prefer Turbine for any UI-state / ViewModel test (almost always
StateFlow
-driven), and
flow.toList()
for repository/transformation tests of cold flows that complete deterministically.
场景选择
能够完成的冷流;“完整列表等于 X”
flow.toList()
(更简洁)
热
StateFlow
/
SharedFlow
Turbine(可正确处理取消)
需要先断言中间状态,再触发更多发射Turbine
需要断言“一段时间内没有更多事件”Turbine(
expectNoEvents
)
需要断言错误类型或完成状态Turbine(
awaitError
、
awaitComplete
)
在一个测试中交错处理多个 FlowTurbine(
turbineScope
/
testIn
)
在 JS/Native 上进行多平台测试两者都可用;Turbine 更简单
不增加任何额外依赖
flow.toList()
(R5。)
经验法则:对于任何 UI state / ViewModel 测试,几乎都应优先使用 Turbine(通常由
StateFlow
驱动);对于能够确定性完成的冷流 repository/转换测试,应使用
flow.toList()
。

Patterns

模式

Pattern: WRONG —
flow.toList()
on a SharedFlow

模式:错误——对 SharedFlow 使用
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()

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

模式:合并的 StateFlow——使用
expectMostRecentItem

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()
    }
}
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
交错处理两个 Flow

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()
    }
}
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
    StateFlow
    /
    SharedFlow
    assertion in
    flow.test { … cancelAndIgnoreRemainingEvents() }
    . MUST NOT call
    flow.toList()
    on a hot flow — the test hangs.
  • MUST call
    cancel()
    /
    cancelAndIgnoreRemainingEvents()
    at the end of every
    test { }
    block over a hot flow.
    awaitComplete()
    is wrong for hot flows — they never complete.
  • MUST account for
    StateFlow
    's seed value: the first
    awaitItem()
    returns the current value (replay = 1). Either assert it or
    skipItems(1)
    .
  • MUST depend on Turbine from
    testImplementation
    only. MUST NOT put
    app.cash.turbine
    on
    implementation
    .
  • MUST override
    withTurbineTimeout(...)
    (or per-call
    timeout =
    ) when the awaited emission genuinely takes more than 3 wall-clock seconds. The 3 s default is wall clock and is independent from
    runTest
    virtual time.
  • MUST use
    cancel()
    (NOT
    awaitComplete()
    ) inside
    testIn
    blocks before
    turbineScope
    ends; otherwise the scope assertion throws.
  • MUST NOT mix Turbine timeouts with
    runTest
    's virtual clock semantics.
    advanceTimeBy(10.minutes)
    is virtual; Turbine's 3-second wait is real.
  • PREFERRED:
    expectMostRecentItem()
    for deterministic "final state" assertions on conflated
    StateFlow
    where intermediate values may be collapsed.
  • PREFERRED: raw
    flow.toList()
    for cold flows that complete deterministically — Turbine is overhead in that case.
  • PREFERRED: name turbines (
    flow.test(name = "uiState")
    ,
    flow.testIn(scope, name = "events")
    ) when more than one runs in a test — error messages cite the name.
  • PREFERRED: the standalone
    Turbine<T>()
    (with
    add
    /
    close
    /
    ensureAllEventsConsumed
    ) over a manually accumulated
    MutableList
    when verifying a
    (T) -> Unit
    callback or a listener was invoked — it gives the same
    awaitItem()
    diagnostics and the unconsumed-event check.
  • PREFERRED: suspending
    awaitItem()
    inside
    runTest
    /
    flow.test
    blocks over the non-suspending
    takeItem()
    /
    takeComplete()
    /
    takeError()
    ; reach for the takers only when the call site genuinely cannot suspend.
  • 必须将所有
    StateFlow
    /
    SharedFlow
    断言包裹在
    flow.test { … cancelAndIgnoreRemainingEvents() }
    中。不得对热流调用
    flow.toList()
    ——测试会挂起。
  • 必须在每个针对热流的
    test { }
    代码块末尾调用
    cancel()
    /
    cancelAndIgnoreRemainingEvents()
    。热流永不完成,因此调用
    awaitComplete()
    是错误的。
  • 必须处理
    StateFlow
    的初始值:第一次
    awaitItem()
    返回当前值(replay = 1)。应断言该值,或在继续断言前调用
    skipItems(1)
    。
  • 必须仅通过
    testImplementation
    依赖 Turbine。不得将
    app.cash.turbine
    放在
    implementation
    中。
  • 如果所等待的发射确实需要超过 3 个挂钟秒,必须覆盖
    withTurbineTimeout(...)
    (或单次调用的
    timeout =
    )。默认的 3 秒采用挂钟时间,与
    runTest
    虚拟时间相互独立。
  • 必须在
    turbineScope
    结束前,于
    testIn
    代码块内调用
    cancel()
    (而不是
    awaitComplete()
    );否则 scope 断言会抛出异常。
  • 不得混用 Turbine 超时与
    runTest
    的虚拟时钟语义。
    advanceTimeBy(10.minutes)
    使用虚拟时间;Turbine 的 3 秒等待使用真实时间。
  • **推荐:**对于会合并中间值的
    StateFlow
    ,当需要确定性的“最终状态”断言时,使用
    expectMostRecentItem()
    。
  • **推荐:**对于能够确定性完成的冷流,使用原始
    flow.toList()
    ——此时 Turbine 属于额外开销。
  • **推荐:**当一个测试中运行多个 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
    flow.toList()
    call exists on any
    StateFlow
    or
    SharedFlow
    (
    grep -rn 'toList()' src/test
    cross-checked against flow types).
  • Every
    flow.test { … }
    over a hot flow ends with
    cancel()
    or
    cancelAndIgnoreRemainingEvents()
    .
  • No
    awaitComplete()
    is called on a
    StateFlow
    /
    SharedFlow
    .
  • StateFlow
    tests either assert the seed via
    awaitItem()
    or
    skipItems(1)
    before further assertions.
  • Turbines that may legitimately wait > 3 s use
    withTurbineTimeout(...)
    or per-call
    timeout = N.seconds
    .
  • Multi-flow tests use
    turbineScope { … testIn(backgroundScope) … }
    rather than nested
    test { }
    blocks.
  • Callback / listener assertions use a standalone
    Turbine<T>()
    (with
    ensureAllEventsConsumed()
    ), not an ad-hoc
    MutableList
    .
  • CI run completes 50 iterations without
    TurbineAssertionError
    flakes.
  • 任何
    StateFlow
    或
    SharedFlow
    上都不存在
    flow.toList()
    调用(通过
    grep -rn 'toList()' src/test
    交叉检查 Flow 类型)。
  • 每个针对热流的
    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 次后仍能完成,且不会出现
    TurbineAssertionError
    flaky failure。

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:
    tasks/research/R5-coroutines-test-turbine.md
    — Turbine API surface, hot/cold contract, comparison with
    toList()
    .
  • docs/CORPUS.md
    §G.1 — Gradle coordinates and version pin.
  • Sibling:
    ../testing-coroutines-with-runtest/SKILL.md
    —
    runTest
    ,
    MainDispatcherRule
    , virtual time foundations Turbine sits on top of.
  • Sibling:
    ../../mocking/mocking-with-mockito/SKILL.md
    — mocking suspend dependencies that produce flows.
  • Sibling:
    ../../mocking/mocking-with-mockk/SKILL.md
    —
    coEvery { repo.items() } returns flowOf(...)
    .
  • Sibling:
    ../../runner/configuring-junit4-on-android/SKILL.md
    — JUnit4 plumbing.
  • 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 sizing for Flow tests.
  • Cross-set:
    ../../../fundamentals/strategies/organizing-test-source-sets/SKILL.md
    — where Flow tests belong (
    src/test/
    ).
  • Cross-set:
    ../../../compose/synchronization/controlling-the-test-clock/SKILL.md
    — Compose's
    MainTestClock
    is independent of Turbine's wall clock.
  • Cross-set:
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    — Turbine works on-device too, with the same API.
  • Cross-set:
    ../../../kotlin/kotlin-test/writing-tests-with-kotlin-test/SKILL.md
    —
    awaitItem()
    paired with
    kotlin.test
    's
    assertEquals
    /
    assertIs
    ; the assertion vocabulary inside
    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:
    tasks/research/R5-coroutines-test-turbine.md
    ——Turbine API、热流/冷流契约,以及与
    toList()
    的比较。
  • docs/CORPUS.md
    §G.1——Gradle 坐标与版本固定。
  • Sibling:
    ../testing-coroutines-with-runtest/SKILL.md
    ——Turbine 所基于的
    runTest
    、
    MainDispatcherRule
    和虚拟时间基础。
  • Sibling:
    ../../mocking/mocking-with-mockito/SKILL.md
    ——模拟会产生 Flow 的 suspend 依赖项。
  • Sibling:
    ../../mocking/mocking-with-mockk/SKILL.md
    ——
    coEvery { repo.items() } returns flowOf(...)
    。
  • Sibling:
    ../../runner/configuring-junit4-on-android/SKILL.md
    ——JUnit4 基础设施。
  • Sibling:
    ../../robolectric/using-robolectric-correctly/SKILL.md
    ——当 SUT 在 JVM 上需要 Android framework 时使用。
  • Cross-set:
    ../../../fundamentals/strategies/applying-testing-strategies/SKILL.md
    ——为 Flow 测试选择小型/中型/大型测试规模。
  • Cross-set:
    ../../../fundamentals/strategies/organizing-test-source-sets/SKILL.md
    ——Flow 测试的存放位置(
    src/test/
    )。
  • Cross-set:
    ../../../compose/synchronization/controlling-the-test-clock/SKILL.md
    ——Compose 的
    MainTestClock
    独立于 Turbine 的挂钟时间。
  • Cross-set:
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    ——Turbine 也可在设备上使用,并提供相同的 API。
  • Cross-set:
    ../../../kotlin/kotlin-test/writing-tests-with-kotlin-test/SKILL.md
    ——将
    awaitItem()
    与
    kotlin.test
    的
    assertEquals
    /
    assertIs
    配合使用;这是
    flow.test { }
    内部的断言表达方式。