synchronizing-with-idle

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Synchronizing With Idle — Pick the Right Wait

使用空闲状态进行同步——选择正确的等待方式

A Compose test that waits on the wrong primitive is the #1 source of flakiness. This skill enumerates every idle/wait API on
ComposeTestRule
and
ComposeUiTest
, locks down what "idle" actually means, and gives a decision matrix for choosing among them. Animation-specific waits live in
../testing-animations-deterministically/SKILL.md
; the underlying clock semantics live in
../controlling-the-test-clock/SKILL.md
.
一个 Compose 测试如果使用了错误的等待原语,就是测试不稳定(flaky)的首要来源。本 skill 枚举了
ComposeTestRule
和
ComposeUiTest
上的每一种 idle/wait API,明确“idle”的实际含义,并提供选择这些 API 的决策矩阵。动画专用等待参见
../testing-animations-deterministically/SKILL.md
;底层时钟语义参见
../controlling-the-test-clock/SKILL.md
。

When to use this skill

何时使用此 skill

  • The test occasionally fails with "node not found" or "node count mismatch" but the production code is correct.
  • The developer reaches for
    Thread.sleep(2000)
    to wait for a screen, a snackbar, a navigation transition, or an IO-backed state.
  • A
    ViewModel
    posts state from a coroutine and the test needs to wait until the UI reflects it.
  • The developer asks about
    IdlingResource
    , the Espresso bridge,
    runOnIdle
    vs
    runOnUiThread
    , or whether
    runWhenIdle
    is faster.
  • The developer mentions
    waitUntil
    ,
    waitUntilExactlyOneExists
    ,
    waitUntilNodeCount
    ,
    AndroidComposeUiTestTimeoutException
    , or
    IdlingPolicies.setMasterPolicyTimeout
    .
  • The developer reads or mutates state from the test thread (e.g.
    state.firstVisibleItemIndex
    ) and asks why it sometimes returns stale data.
  • 测试偶尔因“node not found”或“node count mismatch”失败,但生产代码本身是正确的。
  • 开发者使用
    Thread.sleep(2000)
    等待屏幕、snackbar、导航转场或由 IO 驱动的状态。
  • ViewModel
    从 coroutine 发布状态,而测试需要等待 UI 反映该状态。
  • 开发者询问
    IdlingResource
    、Espresso 桥接、
    runOnIdle
    与
    runOnUiThread
    的区别,或者
    runWhenIdle
    是否更快。
  • 开发者提到
    waitUntil
    、
    waitUntilExactlyOneExists
    、
    waitUntilNodeCount
    、
    AndroidComposeUiTestTimeoutException
    或
    IdlingPolicies.setMasterPolicyTimeout
    。
  • 开发者从测试线程读取或修改状态,例如
    state.firstVisibleItemIndex
    ,并询问为什么有时会返回过期数据。

When NOT to use this skill

何时不应使用此 skill

  • The condition is a paused-clock animation. Use
    ../testing-animations-deterministically/SKILL.md
    and
    mainClock.advanceTimeUntil
    .
  • The mechanics of
    MainTestClock
    itself (frames, rounding, dispatchers) are unclear. Read
    ../controlling-the-test-clock/SKILL.md
    first.
  • The test is failing because of test-tag/finder issues, not async timing. Use
    ../../debug/printing-the-semantics-tree/SKILL.md
    and
    ../../finders/finding-nodes-by-tag-text-content/SKILL.md
    .
  • Espresso interop is the actual question. Use
    ../../interop/testing-with-espresso-interop/SKILL.md
    (sibling skill, separate scope).
  • 等待条件是暂停时钟控制的动画。使用
    ../testing-animations-deterministically/SKILL.md
    和
    mainClock.advanceTimeUntil
    。
  • 不清楚
    MainTestClock
    本身的机制(帧、取整、dispatcher 等)。请先阅读
    ../controlling-the-test-clock/SKILL.md
    。
  • 测试失败是因为 test-tag/finder 使用有误,而不是异步时序问题。使用
    ../../debug/printing-the-semantics-tree/SKILL.md
    和
    ../../finders/finding-nodes-by-tag-text-content/SKILL.md
    。
  • 真正的问题是 Espresso 互操作。使用
    ../../interop/testing-with-espresso-interop/SKILL.md
    (同级 skill,范围独立)。

Prerequisites

前置条件

  • androidx.compose.ui:ui-test
    and
    androidx.compose.ui:ui-test-junit4
    (or
    runComposeUiTest
    ).
  • A
    ComposeContestTestRule
    from
    createComposeRule()
    (PREFERRED v2:
    androidx.compose.ui.test.junit4.v2.createComposeRule
    ).
  • For experimental
    waitUntilNodeCount
    /
    waitUntilExactlyOneExists
    /
    waitUntilAtLeastOneExists
    /
    waitUntilDoesNotExist
    :
    @OptIn(ExperimentalTestApi::class)
    on the test class or method.
  • androidx.compose.ui:ui-test
    和
    androidx.compose.ui:ui-test-junit4
    (或
    runComposeUiTest
    )。
  • 通过
    createComposeRule()
    创建的
    ComposeContestTestRule
    (首选 v2:
    androidx.compose.ui.test.junit4.v2.createComposeRule
    )。
  • 对于实验性 API
    waitUntilNodeCount
    、
    waitUntilExactlyOneExists
    、
    waitUntilAtLeastOneExists
    和
    waitUntilDoesNotExist
    :在测试类或测试方法上添加
    @OptIn(ExperimentalTestApi::class)
    。

What "idle" means

“idle”的含义

Three conditions, all true at once (
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/ComposeUiTest.kt:174-186
):
  1. No pending recompositions. No snapshot apply notifications outstanding, no recomposer pending work, no
    withFrameNanos
    awaiters on the test frame clock.
  2. No pending draw call. Measure and layout passes have run; on Android the draw pass has been requested by the framework (Choreographer drives draw on Android, the test clock does not —
    MainTestClock.kt:36-41
    ).
  3. All registered
    IdlingResource
    s report
    isIdleNow == true
    .
    This is how non-Compose async work (an
    OkHttp
    call, a
    Room
    query) participates in synchronization.
Compose's own work registers automatically through
ComposeIdlingResource
(
compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeIdlingResource.android.kt
), which drains the recomposer + snapshot + frame-clock awaiters in a loop capped at 100 frames per call (line 109). A test that needs more than 100 frames to settle is doing too much per
waitForIdle
.
以下三个条件必须同时成立(
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/ComposeUiTest.kt:174-186
):
  1. 没有待处理的重组。 没有尚未处理的快照应用通知,
    recomposer
    没有待处理工作,测试帧时钟上也没有
    withFrameNanos
    等待者。
  2. 没有待执行的绘制调用。 Measure 和 layout pass 已经执行;在 Android 上,绘制 pass 已由框架请求(Android 上由
    Choreographer
    驱动绘制,测试时钟不负责驱动——
    MainTestClock.kt:36-41
    )。
  3. 所有已注册的
    IdlingResource
    都报告
    isIdleNow == true
    。
    非 Compose 异步工作(例如
    OkHttp
    请求或
    Room
    查询)通过这种方式参与同步。
Compose 自身的工作通过
ComposeIdlingResource
自动注册(
compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeIdlingResource.android.kt
),它会通过循环清空
recomposer
、快照和帧时钟等待者,每次调用最多处理 100 帧(第 109 行)。如果测试需要超过 100 帧才能稳定下来,说明单次
waitForIdle
承担的工作过多。

The primitive surface

原语 API 一览

Every entry below is from
ComposeUiTest.kt
/
ComposeTestRule.jvmAndAndroid.kt
.
APIEffectTimeout source
waitForIdle()
Blocks current thread until the three idle conditions hold. With
autoAdvance = true
, also auto-advances the clock to drain pending work.
Wall clock —
IdlingPolicies.getMasterIdlingPolicy()
awaitIdle()
suspend
variant of
waitForIdle
.
Same
waitUntil(conditionDescription, timeoutMillis = 1_000, condition)
Blocks until
condition()
returns
true
. Each iteration calls
mainClock.advanceTimeByFrame()
(when
autoAdvance == true
) AND
Thread.sleep(10)
wall clock (
ComposeUiTest.android.kt:899-902
). The timeout is measured against
System.nanoTime()
, so it expires on wall-clock time even though the test clock also advances.
Wall clock — per-call
timeoutMillis
waitUntilNodeCount(matcher, count, timeoutMillis = 1_000L)
@ExperimentalTestApi
.
waitUntil
over
onAllNodes(matcher).fetchSemanticsNodes(atLeastOneRootRequired = false).size == count
(
ComposeUiTest.kt:275-285
).
Wall clock
waitUntilExactlyOneExists(matcher, timeoutMillis = 1_000L)
@ExperimentalTestApi
. Sugar for
waitUntilNodeCount(matcher, 1, timeoutMillis)
.
Wall clock
waitUntilAtLeastOneExists(matcher, timeoutMillis = 1_000L)
@ExperimentalTestApi
. (
ComposeUiTest.kt:298-305
)
Wall clock
waitUntilDoesNotExist(matcher, timeoutMillis = 1_000L)
@ExperimentalTestApi
. Sugar for
waitUntilNodeCount(matcher, 0, timeoutMillis)
.
Wall clock
runOnIdle { … }
waitForIdle()
then
runOnUiThread { … }
. The default for state mutations and reads.
Wall clock (the inner
waitForIdle
)
runOnUiThread { … }
Posts a
FutureTask
via
Instrumentation.runOnMainSync
(
AndroidSynchronization.android.kt
). If already on the UI thread, runs in-place. Does NOT wait for idle.
None
runWhenIdle { … }
waitForIdle()
then
runOnUiThread { … }
, but suppresses the implicit
waitForIdle
triggered by node queries inside the lambda. Faster for assert-only blocks. MUST NOT mutate state inside.
Wall clock
awaitAndRunWhenIdle { … }
suspend
variant of
runWhenIdle
.
Wall clock
hasPendingWork(): Boolean
Passive snapshot: are there awaiters on the main clock, snapshot changes, or recomposer pending work? Reliable only when
autoAdvance = false
(
ComposeUiTest.kt:251-256
).
None
IdlingResource
registration
rule.registerIdlingResource(myResource)
/
unregisterIdlingResource
.
Wall clock
以下每一项都来自
ComposeUiTest.kt
/
ComposeTestRule.jvmAndAndroid.kt
。
API效果超时来源
waitForIdle()
阻塞当前线程,直到三个空闲条件全部成立。
autoAdvance = true
时,还会自动推进时钟以清空待处理工作。
墙钟时间——
IdlingPolicies.getMasterIdlingPolicy()
awaitIdle()
waitForIdle
的
suspend
变体。
相同
waitUntil(conditionDescription, timeoutMillis = 1_000, condition)
阻塞 until
condition()
返回
true
。每次迭代都会调用
mainClock.advanceTimeByFrame()
(当
autoAdvance == true
时)并且在墙钟时间上执行
Thread.sleep(10)
(
ComposeUiTest.android.kt:899-902
)。超时通过
System.nanoTime()
测量,因此即使测试时钟同时在推进,超时仍按墙钟时间到期。
墙钟时间——单次调用传入的
timeoutMillis
waitUntilNodeCount(matcher, count, timeoutMillis = 1_000L)
@ExperimentalTestApi
。本质上是
waitUntil
,条件为
onAllNodes(matcher).fetchSemanticsNodes(atLeastOneRootRequired = false).size == count
(
ComposeUiTest.kt:275-285
)。
墙钟时间
waitUntilExactlyOneExists(matcher, timeoutMillis = 1_000L)
@ExperimentalTestApi
。
waitUntilNodeCount(matcher, 1, timeoutMillis)
的语法糖。
墙钟时间
waitUntilAtLeastOneExists(matcher, timeoutMillis = 1_000L)
@ExperimentalTestApi
。(
ComposeUiTest.kt:298-305
)
墙钟时间
waitUntilDoesNotExist(matcher, timeoutMillis = 1_000L)
@ExperimentalTestApi
。
waitUntilNodeCount(matcher, 0, timeoutMillis)
的语法糖。
墙钟时间
runOnIdle { … }
先执行
waitForIdle()
,再执行
runOnUiThread { … }
。读取和修改状态的默认选择。
墙钟时间(内部的
waitForIdle
)
runOnUiThread { … }
通过
Instrumentation.runOnMainSync
提交
FutureTask
(
AndroidSynchronization.android.kt
)。如果已经位于 UI 线程,则原地执行。不会等待进入空闲状态。
无
runWhenIdle { … }
先执行
waitForIdle()
,再执行
runOnUiThread { … }
,但会抑制 lambda 内节点查询触发的隐式
waitForIdle
。对于仅包含断言的代码块速度更快。内部不得修改状态。
墙钟时间
awaitAndRunWhenIdle { … }
runWhenIdle
的
suspend
变体。
墙钟时间
hasPendingWork(): Boolean
被动快照:主时钟上是否存在等待者、是否存在快照变更或
recomposer
待处理工作?仅当
autoAdvance = false
时可靠
(
ComposeUiTest.kt:251-256
)。
无
IdlingResource
注册
rule.registerIdlingResource(myResource)
/
unregisterIdlingResource
。
墙钟时间

Timeout sources — do not mix them

超时来源——不要混用

APISourceDefaultOverride
waitForIdle
/
awaitIdle
Wall clock — Espresso
IdlingPolicies
master timeout
26 s
IdlingPolicies.setMasterPolicyTimeout(...)
in
@Before
waitUntil(…)
family
Wall clock1000 ms per callper-call
timeoutMillis
MainTestClock.advanceTimeUntil(…)
Test clock1000 ms per callper-call
timeoutMillis
runComposeUiTest(testTimeout = …)
Wall clock
60.seconds
runComposeUiTest(testTimeout = 5.minutes) { … }
; throws
AndroidComposeUiTestTimeoutException
Skydoves hot take #4:
waitUntil
timeouts are wall clock;
advanceTimeUntil
is test clock. Always prefer
mainClock.advanceTimeUntil
when the awaited condition is observable through Compose state. Reserve
waitUntil
for conditions outside Compose's snapshot system — a
Job.isCompleted
, a counter incremented from a
LaunchedEffect
, an external service.
RobolectricIdlingStrategy
reads the same Espresso
IdlingPolicies.getMasterIdlingPolicy()
, so a global
setMasterPolicyTimeout
lift applies to host (Robolectric) and device tests alike.
API来源默认值覆盖方式
waitForIdle
/
awaitIdle
墙钟时间——Espresso
IdlingPolicies
主超时
26 秒在
@Before
中调用
IdlingPolicies.setMasterPolicyTimeout(...)
waitUntil(…)
系列
墙钟时间每次调用 1000 ms单次调用传入
timeoutMillis
MainTestClock.advanceTimeUntil(…)
测试时钟每次调用 1000 ms单次调用传入
timeoutMillis
runComposeUiTest(testTimeout = …)
墙钟时间
60.seconds
runComposeUiTest(testTimeout = 5.minutes) { … }
;抛出
AndroidComposeUiTestTimeoutException
Skydoves 热门观点 #4:
waitUntil
的超时按墙钟时间计算;
advanceTimeUntil
按测试时钟计算。只要等待条件能够通过 Compose 状态观察到,就始终优先使用
mainClock.advanceTimeUntil
。仅当条件位于 Compose 快照系统之外时,才使用
waitUntil
,例如
Job.isCompleted
、由
LaunchedEffect
递增的计数器或外部服务。
RobolectricIdlingStrategy
读取同一个 Espresso
IdlingPolicies.getMasterIdlingPolicy()
,因此全局调用
setMasterPolicyTimeout
提升超时时,主机(Robolectric)测试和设备测试都会生效。

Espresso bridge

Espresso 桥接

Espresso has its own
androidx.test.espresso.IdlingResource
interface, which is not the same as Compose's
androidx.compose.ui.test.IdlingResource
. The bridge is
EspressoLink
(
compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/EspressoLink.android.kt
):
text
Espresso (instrumentation tests)
        │ withStrategy { … }
        ▼
EspressoLink   ──implements──>  androidx.test.espresso.IdlingResource
        │
        │  delegates isIdleNow() to ──>  IdlingResourceRegistry
        ▼
IdlingResourceRegistry — Compose's registry
        │
        ├── ComposeIdlingResource   (recomposer + snapshot + frame-clock awaiters)
        └── any rule.registerIdlingResource(...)
The same registry is read by
RobolectricIdlingStrategy
for host tests. The developer registers a Compose
IdlingResource
; the framework does the bridging.
kotlin
interface IdlingResource {
    val isIdleNow: Boolean
    fun getDiagnosticMessageIfBusy(): String? = null
}
(From
compose/ui/ui-test/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/IdlingResource.kt:37-52
.) Override
getDiagnosticMessageIfBusy()
to surface a useful message when a wait times out — it is appended to the timeout exception text.
Espresso 有自己的
androidx.test.espresso.IdlingResource
接口,它与 Compose 的
androidx.compose.ui.test.IdlingResource
不是同一个接口。桥接机制是
EspressoLink
(
compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/EspressoLink.android.kt
):
text
Espresso (instrumentation tests)
        │ withStrategy { … }
        ▼
EspressoLink   ──implements──>  androidx.test.espresso.IdlingResource
        │
        │  delegates isIdleNow() to ──>  IdlingResourceRegistry
        ▼
IdlingResourceRegistry — Compose's registry
        │
        ├── ComposeIdlingResource   (recomposer + snapshot + frame-clock awaiters)
        └── any rule.registerIdlingResource(...)
主机测试中的
RobolectricIdlingStrategy
也会读取同一个 registry。开发者注册的是 Compose
IdlingResource
,框架会自动完成桥接。
kotlin
interface IdlingResource {
    val isIdleNow: Boolean
    fun getDiagnosticMessageIfBusy(): String? = null
}
(摘自
compose/ui/ui-test/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/IdlingResource.kt:37-52
。)重写
getDiagnosticMessageIfBusy()
,可以在等待超时时提供有用的信息;该信息会追加到超时异常文本中。

Decision matrix

决策矩阵

Need to wait for…                         | Use
------------------------------------------|----------------------------------------------
A node count to stabilize                 | waitUntilNodeCount / waitUntilExactlyOneExists
A node to appear                          | waitUntilAtLeastOneExists
A node to disappear                       | waitUntilDoesNotExist
A Compose state condition                 | mainClock.advanceTimeUntil { state }
A non-Compose condition (Job, counter)    | waitUntil(conditionDescription) { condition }
"Just settle the UI"                      | waitForIdle()  (or runOnIdle for read+act)
External async work (HTTP, DB)            | rule.registerIdlingResource(MyIdlingResource)
A paused-clock animation frame            | mainClock.advanceTimeBy(...)  -- different skill
A particular state.value to read safely   | rule.runOnIdle { state.value }
Need to wait for…                         | Use
------------------------------------------|----------------------------------------------
A node count to stabilize                 | waitUntilNodeCount / waitUntilExactlyOneExists
A node to appear                          | waitUntilAtLeastOneExists
A node to disappear                       | waitUntilDoesNotExist
A Compose state condition                 | mainClock.advanceTimeUntil { state }
A non-Compose condition (Job, counter)    | waitUntil(conditionDescription) { condition }
"Just settle the UI"                      | waitForIdle()  (or runOnIdle for read+act)
External async work (HTTP, DB)            | rule.registerIdlingResource(MyIdlingResource)
A paused-clock animation frame            | mainClock.advanceTimeBy(...)  -- different skill
A particular state.value to read safely   | rule.runOnIdle { state.value }

Workflow

工作流

1. Default to
runOnIdle
for state interaction

1. 默认使用
runOnIdle
进行状态交互

Reading or mutating Compose state from the test thread races the recomposer. The recomposer applies snapshot writes on the main thread; the test thread can observe a half-applied state.
runOnIdle
solves this by waiting for idle then dispatching to the UI thread:
kotlin
val firstVisibleIndex = rule.runOnIdle { state.firstVisibleItemIndex }
(skydoves hot take #5 — funnel state mutations through
runOnIdle
or
runOnUiThread
.)
从测试线程读取或修改 Compose 状态会与
recomposer
产生竞态。
recomposer
在主线程应用快照写入,而测试线程可能观察到只应用了一部分的状态。
runOnIdle
会先等待进入空闲状态,再将操作调度到 UI 线程,从而解决这个问题:
kotlin
val firstVisibleIndex = rule.runOnIdle { state.firstVisibleItemIndex }
(Skydoves 热门观点 #5——所有状态修改都应通过
runOnIdle
或
runOnUiThread
执行。)

2. Reach for
runWhenIdle
for read-only assertion blocks

2. 对于只读断言代码块,使用
runWhenIdle

kotlin
rule.runWhenIdle {
    val node = rule.onNodeWithTag("counter").fetchSemanticsNode()
    assertEquals("3", node.config[SemanticsProperties.Text].first().text)
    val rect = node.boundsInRoot
    // ... more reads ...
}
Each node query inside a normal
runOnIdle
re-runs
waitForIdle()
. Inside
runWhenIdle
, those implicit waits are suppressed because the block already entered with idle witnessed. This matters for tests that step frames manually — node queries inside
runOnIdle
would call
waitForIdle()
repeatedly, which (under
autoAdvance = true
) auto-advances the clock and undoes the test's manual control. MUST NOT mutate state inside
runWhenIdle
.
kotlin
rule.runWhenIdle {
    val node = rule.onNodeWithTag("counter").fetchSemanticsNode()
    assertEquals("3", node.config[SemanticsProperties.Text].first().text)
    val rect = node.boundsInRoot
    // ... more reads ...
}
普通
runOnIdle
中的每次节点查询都会重新执行
waitForIdle()
。在
runWhenIdle
中,由于代码块进入时已经确认处于空闲状态,这些隐式等待会被抑制。这一点对于手动推进帧的测试尤其重要:
runOnIdle
中的节点查询会反复调用
waitForIdle()
,而在
autoAdvance = true
时,这会自动推进时钟并破坏测试对手动时钟的控制。内部不得修改状态。

3. Reach for the experimental
waitUntilExactlyOneExists
/ friends for "wait until N nodes match"

3. 对于“等待直到 N 个节点匹配”,使用实验性的
waitUntilExactlyOneExists
等 API

kotlin
@OptIn(ExperimentalTestApi::class)
@Test fun snackbarAppears() {
    rule.setContent { /* … triggers a snackbar after 200 ms … */ }
    rule.onNodeWithTag("trigger").performClick()
    rule.waitUntilExactlyOneExists(hasTestTag("snackbar"), timeoutMillis = 2_000)
    rule.onNodeWithTag("snackbar").assertTextEquals("Saved")
}
The default 1000 ms timeout (
ComposeUiTest.kt:278
,
ComposeUiTest.kt:301
,
ComposeUiTest.kt:321
,
ComposeUiTest.kt:334
) is often too tight for snackbars and bottom-sheet animations. Lift it explicitly per call.
kotlin
@OptIn(ExperimentalTestApi::class)
@Test fun snackbarAppears() {
    rule.setContent { /* … triggers a snackbar after 200 ms … */ }
    rule.onNodeWithTag("trigger").performClick()
    rule.waitUntilExactlyOneExists(hasTestTag("snackbar"), timeoutMillis = 2_000)
    rule.onNodeWithTag("snackbar").assertTextEquals("Saved")
}
默认的 1000 ms 超时(
ComposeUiTest.kt:278
、
ComposeUiTest.kt:301
、
ComposeUiTest.kt:321
、
ComposeUiTest.kt:334
)对于 snackbar 和 bottom-sheet 动画而言通常过短。应在每次调用时显式延长超时时间。

4. Reach for
waitUntil { … }
only for non-Compose conditions

4. 仅对非 Compose 条件使用
waitUntil { … }

kotlin
// SnackbarHostTest.kt:77-88
val job = scope.launch {
    hostState.showSnackbar("1")
    Truth.assertThat(resultedInvocation).isEqualTo("1")
    hostState.showSnackbar("2")
    Truth.assertThat(resultedInvocation).isEqualTo("12")
    hostState.showSnackbar("3")
    Truth.assertThat(resultedInvocation).isEqualTo("123")
}
rule.waitUntil { job.isCompleted }
Job.isCompleted
is not Compose state;
mainClock.advanceTimeUntil { job.isCompleted }
would loop and time out because no amount of clock advancement makes the
Job
complete on its own.
kotlin
// SnackbarHostTest.kt:77-88
val job = scope.launch {
    hostState.showSnackbar("1")
    Truth.assertThat(resultedInvocation).isEqualTo("1")
    hostState.showSnackbar("2")
    Truth.assertThat(resultedInvocation).isEqualTo("12")
    hostState.showSnackbar("3")
    Truth.assertThat(resultedInvocation).isEqualTo("123")
}
rule.waitUntil { job.isCompleted }
Job.isCompleted
不是 Compose 状态;使用
mainClock.advanceTimeUntil { job.isCompleted }
会不断循环并最终超时,因为无论推进多少时钟,都无法让
Job
自行完成。

5. Register an
IdlingResource
for genuine external async work

5. 为真正的外部异步工作注册
IdlingResource

kotlin
class HttpIdlingResource(private val client: OkHttpClient) : IdlingResource {
    override val isIdleNow: Boolean
        get() = client.dispatcher.runningCallsCount() == 0
    override fun getDiagnosticMessageIfBusy(): String? =
        "${client.dispatcher.runningCallsCount()} HTTP calls still in flight"
}

@Before fun setUp() { rule.registerIdlingResource(HttpIdlingResource(client)) }
@After  fun tearDown() { rule.unregisterIdlingResource(HttpIdlingResource(client)) }
After registration, every
waitForIdle
(and the implicit
waitForIdle
inside every node query) will block until
isIdleNow == true
. MUST keep
isIdleNow
lightweight — it is called from the main thread (
IdlingResource.kt:38-46
).
kotlin
class HttpIdlingResource(private val client: OkHttpClient) : IdlingResource {
    override val isIdleNow: Boolean
        get() = client.dispatcher.runningCallsCount() == 0
    override fun getDiagnosticMessageIfBusy(): String? =
        "${client.dispatcher.runningCallsCount()} HTTP calls still in flight"
}

@Before fun setUp() { rule.registerIdlingResource(HttpIdlingResource(client)) }
@After  fun tearDown() { rule.unregisterIdlingResource(HttpIdlingResource(client)) }
注册之后,每次
waitForIdle
以及每次节点查询内部隐式执行的
waitForIdle
,都会阻塞到
isIdleNow == true
为止。必须确保
isIdleNow
足够轻量,因为它会在主线程中被调用(
IdlingResource.kt:38-46
)。

Patterns

模式

Pattern: WRONG —
Thread.sleep
to wait for a node

模式:错误——使用
Thread.sleep
等待节点

kotlin
// WRONG
@Test fun successScreen() {
    rule.setContent { App() }
    rule.onNodeWithTag("login").performClick()
    Thread.sleep(2_000)
    rule.onNodeWithTag("dashboard").assertExists()
}
// WRONG because: Thread.sleep is unrelated to Compose's synchronization. It either over-
// waits (slowing the test) or under-waits (flake when CI is slow). Compose's own
// IdlingResource is already wired; just wait on the node directly.
kotlin
// RIGHT
@OptIn(ExperimentalTestApi::class)
@Test fun successScreen() {
    rule.setContent { App() }
    rule.onNodeWithTag("login").performClick()
    rule.waitUntilExactlyOneExists(hasTestTag("dashboard"), timeoutMillis = 2_000)
    rule.onNodeWithTag("dashboard").assertExists()
}
kotlin
// WRONG
@Test fun successScreen() {
    rule.setContent { App() }
    rule.onNodeWithTag("login").performClick()
    Thread.sleep(2_000)
    rule.onNodeWithTag("dashboard").assertExists()
}
// WRONG because: Thread.sleep is unrelated to Compose's synchronization. It either over-
// waits (slowing the test) or under-waits (flake when CI is slow). Compose's own
// IdlingResource is already wired; just wait on the node directly.
kotlin
// RIGHT
@OptIn(ExperimentalTestApi::class)
@Test fun successScreen() {
    rule.setContent { App() }
    rule.onNodeWithTag("login").performClick()
    rule.waitUntilExactlyOneExists(hasTestTag("dashboard"), timeoutMillis = 2_000)
    rule.onNodeWithTag("dashboard").assertExists()
}

Pattern: WRONG —
waitUntil
for a Compose-state-observable condition

模式:错误——对可通过 Compose 状态观察到的条件使用
waitUntil

kotlin
// WRONG
rule.waitUntil(timeoutMillis = 5_000) { state.value == Phase.Done }
// WRONG because: timeout is measured in wall clock and each iteration burns ~10 ms
// of real time on Thread.sleep(10) (ComposeUiTest.android.kt:899-902). For a Compose
// state condition, advanceTimeUntil drives the test clock and is deterministic.
kotlin
// RIGHT
rule.mainClock.advanceTimeUntil(timeoutMillis = 5_000) { state.value == Phase.Done }
(skydoves hot take #4.)
kotlin
// WRONG
rule.waitUntil(timeoutMillis = 5_000) { state.value == Phase.Done }
// WRONG because: timeout is measured in wall clock and each iteration burns ~10 ms
// of real time on Thread.sleep(10) (ComposeUiTest.android.kt:899-902). For a Compose
// state condition, advanceTimeUntil drives the test clock and is deterministic.
kotlin
// RIGHT
rule.mainClock.advanceTimeUntil(timeoutMillis = 5_000) { state.value == Phase.Done }
(Skydoves 热门观点 #4。)

Pattern: WRONG — reading state from the test thread

模式:错误——从测试线程读取状态

kotlin
// WRONG
val i = state.firstVisibleItemIndex
assertEquals(2, i)
// WRONG because: the test thread races the recomposer. The read may observe a half-applied
// snapshot, especially right after a click or scroll. Compose's docs are explicit: state
// reads from outside the UI thread are not synchronized.
kotlin
// RIGHT
val i = rule.runOnIdle { state.firstVisibleItemIndex }
assertEquals(2, i)
(skydoves hot take #5.)
kotlin
// WRONG
val i = state.firstVisibleItemIndex
assertEquals(2, i)
// WRONG because: the test thread races the recomposer. The read may observe a half-applied
// snapshot, especially right after a click or scroll. Compose's docs are explicit: state
// reads from outside the UI thread are not synchronized.
kotlin
// RIGHT
val i = rule.runOnIdle { state.firstVisibleItemIndex }
assertEquals(2, i)
(Skydoves 热门观点 #5。)

Pattern:
hasPendingWork()
— passive check, paused-clock only

模式:
hasPendingWork()
——被动检查,仅适用于暂停时钟

kotlin
rule.mainClock.autoAdvance = false
rule.setContent { /* … */ }
rule.mainClock.advanceTimeByFrame()
rule.runOnUiThread { trigger = true }
assertTrue(rule.hasPendingWork())              // recomposition queued, no frame yet
rule.mainClock.advanceTimeByFrame()
assertFalse(rule.hasPendingWork())             // frame applied
From
ComposeUiTest.kt:251-256
:
If
autoAdvance
is
true
, the testing framework continuously processes pending work. In that scenario, calling this method acts as a momentary snapshot and will generally return
false
. It may briefly return
true
if work is queued but the framework hasn't auto-advanced yet, making the result fleeting and unreliable for driving test logic.
MUST NOT drive test logic off
hasPendingWork()
while
autoAdvance == true
.
kotlin
rule.mainClock.autoAdvance = false
rule.setContent { /* … */ }
rule.mainClock.advanceTimeByFrame()
rule.runOnUiThread { trigger = true }
assertTrue(rule.hasPendingWork())              // recomposition queued, no frame yet
rule.mainClock.advanceTimeByFrame()
assertFalse(rule.hasPendingWork())             // frame applied
摘自
ComposeUiTest.kt:251-256
:
如果
autoAdvance
为
true
,测试框架会持续处理待处理工作。在这种情况下,调用此方法相当于获取瞬时快照,通常会返回
false
。如果工作已经排队但框架尚未自动推进,它也可能短暂返回
true
,因此该结果转瞬即逝,不适合用来驱动测试逻辑。
当
autoAdvance == true
时,不得依赖
hasPendingWork()
驱动测试逻辑。

Pattern: lift the master idling timeout for slow CI

模式:为较慢的 CI 提高主 idle 超时

kotlin
@Before fun setUp() {
    IdlingPolicies.setMasterPolicyTimeout(60, TimeUnit.SECONDS)
}
Apply when
waitForIdle
(not
waitUntil
) times out on CI but passes locally. Both
EspressoLink
and
RobolectricIdlingStrategy
honor this policy.
kotlin
@Before fun setUp() {
    IdlingPolicies.setMasterPolicyTimeout(60, TimeUnit.SECONDS)
}
当
waitForIdle
(而不是
waitUntil
)在 CI 上超时、但本地可以通过时,可以采用此方式。
EspressoLink
和
RobolectricIdlingStrategy
都会遵循该策略。

Mandatory rules

强制规则

  • MUST prefer
    mainClock.advanceTimeUntil { state }
    over
    rule.waitUntil { state }
    whenever the awaited condition is a Compose-state read (skydoves hot take #4).
  • MUST wrap state reads from the test thread in
    runOnIdle { … }
    or
    runOnUiThread { … }
    . Direct
    state.value
    reads from the test thread race the recomposer (skydoves hot take #5).
  • MUST call
    runOnUiThread
    (not
    runOnIdle
    ) for state mutations under a paused clock (
    autoAdvance = false
    );
    runOnIdle
    's implicit
    waitForIdle
    is wrong for that mode. See
    ../testing-animations-deterministically/SKILL.md
    .
  • MUST use
    runWhenIdle { … }
    for assert-only blocks that do many node reads — it suppresses the redundant per-query
    waitForIdle
    . MUST NOT mutate state inside.
  • MUST prefer
    waitUntilExactlyOneExists
    /
    waitUntilAtLeastOneExists
    /
    waitUntilDoesNotExist
    over hand-rolled
    waitUntil { onAllNodes(...).fetchSemanticsNodes().isNotEmpty() }
    . They are clearer and cite a
    conditionDescription
    in the timeout message.
  • MUST NOT treat
    hasPendingWork()
    as actionable while
    autoAdvance == true
    . It is a passive snapshot; reliable only with the clock paused (
    ComposeUiTest.kt:251-256
    ).
  • MUST NOT use
    Thread.sleep
    to wait for state to settle. Replace with
    waitUntil*
    ,
    mainClock.advanceTimeUntil
    , or an
    IdlingResource
    (skydoves hot take #7). The one legitimate
    Thread.sleep
    is on the RenderThread for ripple/screenshot tests.
  • PREFERRED: an
    IdlingResource
    per genuine external async source (HTTP, DB, an external counter), registered in
    @Before
    and unregistered in
    @After
    . Override
    getDiagnosticMessageIfBusy()
    so timeout messages are useful.
  • PREFERRED:
    IdlingPolicies.setMasterPolicyTimeout(...)
    in
    @Before
    for CI flakes due to slow agents — uniformly lifts both Espresso and Robolectric.
  • 只要等待条件是 Compose 状态读取,必须优先使用
    mainClock.advanceTimeUntil { state }
    ,而不是
    rule.waitUntil { state }
    (Skydoves 热门观点 #4)。
  • 必须将测试线程中的状态读取包装在
    runOnIdle { … }
    或
    runOnUiThread { … }
    中。直接从测试线程读取
    state.value
    会与
    recomposer
    产生竞态(Skydoves 热门观点 #5)。
  • 在暂停时钟(
    autoAdvance = false
    )下修改状态时,必须调用
    runOnUiThread
    ,而不是
    runOnIdle
    ;此模式不适合使用
    runOnIdle
    隐式执行的
    waitForIdle
    。参见
    ../testing-animations-deterministically/SKILL.md
    。
  • 必须在包含大量节点读取的仅断言代码块中使用
    runWhenIdle { … }
    ,以抑制每次查询产生的冗余
    waitForIdle
    。不得在其中修改状态。
  • 必须优先使用
    waitUntilExactlyOneExists
    、
    waitUntilAtLeastOneExists
    或
    waitUntilDoesNotExist
    ,而不是手动编写
    waitUntil { onAllNodes(...).fetchSemanticsNodes().isNotEmpty() }
    。前者的意图更清晰,并且能在超时消息中提供
    conditionDescription
    。
  • 当
    autoAdvance == true
    时,不得将
    hasPendingWork()
    的结果作为可执行依据。它只是被动快照,仅在时钟暂停时可靠(
    ComposeUiTest.kt:251-256
    )。
  • 不得使用
    Thread.sleep
    等待状态稳定。应改用
    waitUntil*
    、
    mainClock.advanceTimeUntil
    或
    IdlingResource
    (Skydoves 热门观点 #7)。唯一合理的
    Thread.sleep
    场景是在 RenderThread 上执行波纹或截图测试。
  • 首选: 为每个真正的外部异步源(HTTP、DB、外部计数器)注册一个
    IdlingResource
    ,在
    @Before
    中注册,并在
    @After
    中注销。重写
    getDiagnosticMessageIfBusy()
    ,以便提供有用的超时消息。
  • 首选: 在
    @Before
    中调用
    IdlingPolicies.setMasterPolicyTimeout(...)
    ,处理由 CI agent 过慢导致的测试不稳定;该设置会统一提高 Espresso 和 Robolectric 的超时时间。

Verification

验证

  • No
    Thread.sleep
    exists in any test method except the documented RenderThread/screenshot exceptions.
  • Every state read from the test thread is wrapped in
    runOnIdle { … }
    (search:
    grep -nP 'state\.\w+' src/androidTest
    ).
  • Every
    waitUntil { state.value … }
    for a Compose-state condition has been migrated to
    mainClock.advanceTimeUntil { state.value … }
    .
  • Every "wait for node" path uses
    waitUntilExactlyOneExists
    /
    waitUntilAtLeastOneExists
    /
    waitUntilDoesNotExist
    rather than a hand-rolled
    waitUntil
    over
    fetchSemanticsNodes()
    .
  • Every external async source has a registered
    IdlingResource
    , registered in
    @Before
    and unregistered in
    @After
    .
  • No call site relies on
    hasPendingWork()
    while
    autoAdvance == true
    .
  • CI run completes 50 iterations without an
    AndroidComposeUiTestTimeoutException
    or
    ComposeTimeoutException
    flake.
  • 除已记录的 RenderThread/截图例外情况外,任何测试方法中都不存在
    Thread.sleep
    。
  • 测试线程中的每次状态读取都包装在
    runOnIdle { … }
    中(搜索:
    grep -nP 'state\.\w+' src/androidTest
    )。
  • 针对 Compose 状态条件的每个
    waitUntil { state.value … }
    都已迁移到
    mainClock.advanceTimeUntil { state.value … }
    。
  • 每条“等待节点”的路径都使用
    waitUntilExactlyOneExists
    、
    waitUntilAtLeastOneExists
    或
    waitUntilDoesNotExist
    ,而不是在
    fetchSemanticsNodes()
    上手动编写
    waitUntil
    。
  • 每个外部异步源都注册了
    IdlingResource
    ,并在
    @Before
    中注册、
    @After
    中注销。
  • 没有调用点在
    autoAdvance == true
    时依赖
    hasPendingWork()
    。
  • CI 连续运行 50 次后,没有出现
    AndroidComposeUiTestTimeoutException
    或
    ComposeTimeoutException
    不稳定问题。

References

参考资料

  • Android Developers — Compose testing: https://developer.android.com/develop/ui/compose/testing
  • Android Developers — Compose testing cheat sheet: https://developer.android.com/develop/ui/compose/testing-cheatsheet
  • Espresso
    IdlingPolicies
    reference: https://developer.android.com/reference/androidx/test/espresso/IdlingPolicies
  • compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/ComposeUiTest.kt:174-260
    —
    waitForIdle
    ,
    awaitIdle
    ,
    waitUntil
    ,
    runOnIdle
    ,
    runOnUiThread
    ,
    runWhenIdle
    ,
    awaitAndRunWhenIdle
    ,
    hasPendingWork
    .
  • compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/ComposeUiTest.kt:275-335
    — the experimental
    waitUntilNodeCount
    /
    waitUntilExactlyOneExists
    /
    waitUntilAtLeastOneExists
    /
    waitUntilDoesNotExist
    extensions.
  • compose/ui/ui-test/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/IdlingResource.kt
    — the public
    IdlingResource
    interface.
  • compose/ui/ui-test/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/IdlingResourceRegistry.jvmAndAndroid.kt
    — the registry that aggregates user-registered resources + Compose's own.
  • compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeIdlingResource.android.kt
    — Compose's automatically-registered resource; 100-frame cap at line 109.
  • compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/EspressoLink.android.kt
    — the
    androidx.test.espresso.IdlingResource
    bridge.
  • compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeUiTest.android.kt:885-908
    —
    waitUntil
    's 10 ms wall-clock poll loop.
  • compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/AndroidSynchronization.android.kt
    —
    runOnUiThread
    posts a
    FutureTask
    via
    Instrumentation.runOnMainSync
    .
  • compose/material3/material3/src/androidDeviceTest/kotlin/androidx/compose/material3/SnackbarHostTest.kt:77-88
    — canonical
    rule.waitUntil { job.isCompleted }
    .
  • Sibling skill:
    ../controlling-the-test-clock/SKILL.md
    —
    MainTestClock
    , frame model,
    advanceTimeUntil
    .
  • Sibling skill:
    ../testing-animations-deterministically/SKILL.md
    — paused-clock animation tests.
  • Sibling skill:
    ../../patterns/structuring-a-compose-test/SKILL.md
    — JUnit lifecycle around idle waits.
  • Sibling skill:
    ../../debug/printing-the-semantics-tree/SKILL.md
    — when "node not found" turns out to be a finder issue, not an async issue.
  • Android Developers——Compose 测试:https://developer.android.com/develop/ui/compose/testing
  • Android Developers——Compose 测试速查表:https://developer.android.com/develop/ui/compose/testing-cheatsheet
  • Espresso
    IdlingPolicies
    参考:https://developer.android.com/reference/androidx/test/espresso/IdlingPolicies
  • compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/ComposeUiTest.kt:174-260
    ——
    waitForIdle
    、
    awaitIdle
    、
    waitUntil
    、
    runOnIdle
    、
    runOnUiThread
    、
    runWhenIdle
    、
    awaitAndRunWhenIdle
    、
    hasPendingWork
    。
  • compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/ComposeUiTest.kt:275-335
    ——实验性扩展
    waitUntilNodeCount
    、
    waitUntilExactlyOneExists
    、
    waitUntilAtLeastOneExists
    、
    waitUntilDoesNotExist
    。
  • compose/ui/ui-test/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/IdlingResource.kt
    ——公开的
    IdlingResource
    接口。
  • compose/ui/ui-test/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/IdlingResourceRegistry.jvmAndAndroid.kt
    ——聚合用户注册资源与 Compose 自身资源的 registry。
  • compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeIdlingResource.android.kt
    ——Compose 自动注册的资源;第 109 行包含 100 帧上限。
  • compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/EspressoLink.android.kt
    ——
    androidx.test.espresso.IdlingResource
    桥接。
  • compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeUiTest.android.kt:885-908
    ——
    waitUntil
    的 10 ms 墙钟时间轮询循环。
  • compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/AndroidSynchronization.android.kt
    ——
    runOnUiThread
    通过
    Instrumentation.runOnMainSync
    提交
    FutureTask
    。
  • compose/material3/material3/src/androidDeviceTest/kotlin/androidx/compose/material3/SnackbarHostTest.kt:77-88
    ——
    rule.waitUntil { job.isCompleted }
    的典型示例。
  • 同级 skill:
    ../controlling-the-test-clock/SKILL.md
    ——
    MainTestClock
    、帧模型和
    advanceTimeUntil
    。
  • 同级 skill:
    ../testing-animations-deterministically/SKILL.md
    ——暂停时钟的动画测试。
  • 同级 skill:
    ../../patterns/structuring-a-compose-test/SKILL.md
    ——围绕 idle 等待组织 JUnit 生命周期。
  • 同级 skill:
    ../../debug/printing-the-semantics-tree/SKILL.md
    ——当“node not found”实际是 finder 问题时使用。