synchronizing-with-idle
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSynchronizing 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 and , locks down what "idle" actually means, and gives a decision matrix for choosing among them. Animation-specific waits live in ; the underlying clock semantics live in .
ComposeTestRuleComposeUiTest../testing-animations-deterministically/SKILL.md../controlling-the-test-clock/SKILL.md一个 Compose 测试如果使用了错误的等待原语,就是测试不稳定(flaky)的首要来源。本 skill 枚举了 和 上的每一种 idle/wait API,明确“idle”的实际含义,并提供选择这些 API 的决策矩阵。动画专用等待参见 ;底层时钟语义参见 。
ComposeTestRuleComposeUiTest../testing-animations-deterministically/SKILL.md../controlling-the-test-clock/SKILL.mdWhen 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 to wait for a screen, a snackbar, a navigation transition, or an IO-backed state.
Thread.sleep(2000) - A posts state from a coroutine and the test needs to wait until the UI reflects it.
ViewModel - The developer asks about , the Espresso bridge,
IdlingResourcevsrunOnIdle, or whetherrunOnUiThreadis faster.runWhenIdle - The developer mentions ,
waitUntil,waitUntilExactlyOneExists,waitUntilNodeCount, orAndroidComposeUiTestTimeoutException.IdlingPolicies.setMasterPolicyTimeout - The developer reads or mutates state from the test thread (e.g. ) and asks why it sometimes returns stale data.
state.firstVisibleItemIndex
- 测试偶尔因“node not found”或“node count mismatch”失败,但生产代码本身是正确的。
- 开发者使用 等待屏幕、snackbar、导航转场或由 IO 驱动的状态。
Thread.sleep(2000) - 从 coroutine 发布状态,而测试需要等待 UI 反映该状态。
ViewModel - 开发者询问 、Espresso 桥接、
IdlingResource与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 and
../testing-animations-deterministically/SKILL.md.mainClock.advanceTimeUntil - The mechanics of itself (frames, rounding, dispatchers) are unclear. Read
MainTestClockfirst.../controlling-the-test-clock/SKILL.md - The test is failing because of test-tag/finder issues, not async timing. Use and
../../debug/printing-the-semantics-tree/SKILL.md.../../finders/finding-nodes-by-tag-text-content/SKILL.md - Espresso interop is the actual question. Use (sibling skill, separate scope).
../../interop/testing-with-espresso-interop/SKILL.md
- 等待条件是暂停时钟控制的动画。使用 和
../testing-animations-deterministically/SKILL.md。mainClock.advanceTimeUntil - 不清楚 本身的机制(帧、取整、dispatcher 等)。请先阅读
MainTestClock。../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 互操作。使用 (同级 skill,范围独立)。
../../interop/testing-with-espresso-interop/SKILL.md
Prerequisites
前置条件
- and
androidx.compose.ui:ui-test(orandroidx.compose.ui:ui-test-junit4).runComposeUiTest - A from
ComposeContestTestRule(PREFERRED v2:createComposeRule()).androidx.compose.ui.test.junit4.v2.createComposeRule - For experimental /
waitUntilNodeCount/waitUntilExactlyOneExists/waitUntilAtLeastOneExists:waitUntilDoesNotExiston the test class or method.@OptIn(ExperimentalTestApi::class)
- 和
androidx.compose.ui:ui-test(或androidx.compose.ui:ui-test-junit4)。runComposeUiTest - 通过 创建的
createComposeRule()(首选 v2:ComposeContestTestRule)。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- No pending recompositions. No snapshot apply notifications outstanding, no recomposer pending work, no awaiters on the test frame clock.
withFrameNanos - 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 - All registered s report
IdlingResource. This is how non-Compose async work (anisIdleNow == truecall, aOkHttpquery) participates in synchronization.Room
Compose's own work registers automatically through (), 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 .
ComposeIdlingResourcecompose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeIdlingResource.android.ktwaitForIdle以下三个条件必须同时成立():
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/ComposeUiTest.kt:174-186- 没有待处理的重组。 没有尚未处理的快照应用通知,没有待处理工作,测试帧时钟上也没有
recomposer等待者。withFrameNanos - 没有待执行的绘制调用。 Measure 和 layout pass 已经执行;在 Android 上,绘制 pass 已由框架请求(Android 上由 驱动绘制,测试时钟不负责驱动——
Choreographer)。MainTestClock.kt:36-41 - 所有已注册的 都报告
IdlingResource。 非 Compose 异步工作(例如isIdleNow == true请求或OkHttp查询)通过这种方式参与同步。Room
Compose 自身的工作通过 自动注册(),它会通过循环清空 、快照和帧时钟等待者,每次调用最多处理 100 帧(第 109 行)。如果测试需要超过 100 帧才能稳定下来,说明单次 承担的工作过多。
ComposeIdlingResourcecompose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeIdlingResource.android.ktrecomposerwaitForIdleThe primitive surface
原语 API 一览
Every entry below is from / .
ComposeUiTest.ktComposeTestRule.jvmAndAndroid.kt| API | Effect | Timeout source |
|---|---|---|
| Blocks current thread until the three idle conditions hold. With | Wall clock — |
| | Same |
| Blocks until | Wall clock — per-call |
| | Wall clock |
| | Wall clock |
| | Wall clock |
| | Wall clock |
| | Wall clock (the inner |
| Posts a | None |
| | Wall clock |
| | Wall clock |
| Passive snapshot: are there awaiters on the main clock, snapshot changes, or recomposer pending work? Reliable only when | None |
| | Wall clock |
以下每一项都来自 / 。
ComposeUiTest.ktComposeTestRule.jvmAndAndroid.kt| API | 效果 | 超时来源 |
|---|---|---|
| 阻塞当前线程,直到三个空闲条件全部成立。 | 墙钟时间—— |
| | 相同 |
| 阻塞 until | 墙钟时间——单次调用传入的 |
| | 墙钟时间 |
| | 墙钟时间 |
| | 墙钟时间 |
| | 墙钟时间 |
| 先执行 | 墙钟时间(内部的 |
| 通过 | 无 |
| 先执行 | 墙钟时间 |
| | 墙钟时间 |
| 被动快照:主时钟上是否存在等待者、是否存在快照变更或 | 无 |
| | 墙钟时间 |
Timeout sources — do not mix them
超时来源——不要混用
| API | Source | Default | Override |
|---|---|---|---|
| Wall clock — Espresso | 26 s | |
| Wall clock | 1000 ms per call | per-call |
| Test clock | 1000 ms per call | per-call |
| Wall clock | | |
Skydoves hot take #4: timeouts are wall clock; is test clock. Always prefer when the awaited condition is observable through Compose state. Reserve for conditions outside Compose's snapshot system — a , a counter incremented from a , an external service.
waitUntiladvanceTimeUntilmainClock.advanceTimeUntilwaitUntilJob.isCompletedLaunchedEffectRobolectricIdlingStrategyIdlingPolicies.getMasterIdlingPolicy()setMasterPolicyTimeout| API | 来源 | 默认值 | 覆盖方式 |
|---|---|---|---|
| 墙钟时间——Espresso | 26 秒 | 在 |
| 墙钟时间 | 每次调用 1000 ms | 单次调用传入 |
| 测试时钟 | 每次调用 1000 ms | 单次调用传入 |
| 墙钟时间 | | |
Skydoves 热门观点 #4: 的超时按墙钟时间计算; 按测试时钟计算。只要等待条件能够通过 Compose 状态观察到,就始终优先使用 。仅当条件位于 Compose 快照系统之外时,才使用 ,例如 、由 递增的计数器或外部服务。
waitUntiladvanceTimeUntilmainClock.advanceTimeUntilwaitUntilJob.isCompletedLaunchedEffectRobolectricIdlingStrategyIdlingPolicies.getMasterIdlingPolicy()setMasterPolicyTimeoutEspresso bridge
Espresso 桥接
Espresso has its own interface, which is not the same as Compose's . The bridge is ():
androidx.test.espresso.IdlingResourceandroidx.compose.ui.test.IdlingResourceEspressoLinkcompose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/EspressoLink.android.kttext
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 for host tests. The developer registers a Compose ; the framework does the bridging.
RobolectricIdlingStrategyIdlingResourcekotlin
interface IdlingResource {
val isIdleNow: Boolean
fun getDiagnosticMessageIfBusy(): String? = null
}(From .) Override to surface a useful message when a wait times out — it is appended to the timeout exception text.
compose/ui/ui-test/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/IdlingResource.kt:37-52getDiagnosticMessageIfBusy()Espresso 有自己的 接口,它与 Compose 的 不是同一个接口。桥接机制是 ():
androidx.test.espresso.IdlingResourceandroidx.compose.ui.test.IdlingResourceEspressoLinkcompose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/EspressoLink.android.kttext
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(...)主机测试中的 也会读取同一个 registry。开发者注册的是 Compose ,框架会自动完成桥接。
RobolectricIdlingStrategyIdlingResourcekotlin
interface IdlingResource {
val isIdleNow: Boolean
fun getDiagnosticMessageIfBusy(): String? = null
}(摘自 。)重写 ,可以在等待超时时提供有用的信息;该信息会追加到超时异常文本中。
compose/ui/ui-test/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/IdlingResource.kt:37-52getDiagnosticMessageIfBusy()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
runOnIdle1. 默认使用 runOnIdle
进行状态交互
runOnIdleReading 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. solves this by waiting for idle then dispatching to the UI thread:
runOnIdlekotlin
val firstVisibleIndex = rule.runOnIdle { state.firstVisibleItemIndex }(skydoves hot take #5 — funnel state mutations through or .)
runOnIdlerunOnUiThread从测试线程读取或修改 Compose 状态会与 产生竞态。 在主线程应用快照写入,而测试线程可能观察到只应用了一部分的状态。 会先等待进入空闲状态,再将操作调度到 UI 线程,从而解决这个问题:
recomposerrecomposerrunOnIdlekotlin
val firstVisibleIndex = rule.runOnIdle { state.firstVisibleItemIndex }(Skydoves 热门观点 #5——所有状态修改都应通过 或 执行。)
runOnIdlerunOnUiThread2. Reach for runWhenIdle
for read-only assertion blocks
runWhenIdle2. 对于只读断言代码块,使用 runWhenIdle
runWhenIdlekotlin
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 re-runs . Inside , those implicit waits are suppressed because the block already entered with idle witnessed. This matters for tests that step frames manually — node queries inside would call repeatedly, which (under ) auto-advances the clock and undoes the test's manual control. MUST NOT mutate state inside .
runOnIdlewaitForIdle()runWhenIdlerunOnIdlewaitForIdle()autoAdvance = truerunWhenIdlekotlin
rule.runWhenIdle {
val node = rule.onNodeWithTag("counter").fetchSemanticsNode()
assertEquals("3", node.config[SemanticsProperties.Text].first().text)
val rect = node.boundsInRoot
// ... more reads ...
}普通 中的每次节点查询都会重新执行 。在 中,由于代码块进入时已经确认处于空闲状态,这些隐式等待会被抑制。这一点对于手动推进帧的测试尤其重要: 中的节点查询会反复调用 ,而在 时,这会自动推进时钟并破坏测试对手动时钟的控制。内部不得修改状态。
runOnIdlewaitForIdle()runWhenIdlerunOnIdlewaitForIdle()autoAdvance = true3. Reach for the experimental waitUntilExactlyOneExists
/ friends for "wait until N nodes match"
waitUntilExactlyOneExists3. 对于“等待直到 N 个节点匹配”,使用实验性的 waitUntilExactlyOneExists
等 API
waitUntilExactlyOneExistskotlin
@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 (, , , ) is often too tight for snackbars and bottom-sheet animations. Lift it explicitly per call.
ComposeUiTest.kt:278ComposeUiTest.kt:301ComposeUiTest.kt:321ComposeUiTest.kt:334kotlin
@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 超时(、、、)对于 snackbar 和 bottom-sheet 动画而言通常过短。应在每次调用时显式延长超时时间。
ComposeUiTest.kt:278ComposeUiTest.kt:301ComposeUiTest.kt:321ComposeUiTest.kt:3344. Reach for waitUntil { … }
only for non-Compose conditions
waitUntil { … }4. 仅对非 Compose 条件使用 waitUntil { … }
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.isCompletedmainClock.advanceTimeUntil { job.isCompleted }Jobkotlin
// 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.isCompletedmainClock.advanceTimeUntil { job.isCompleted }Job5. Register an IdlingResource
for genuine external async work
IdlingResource5. 为真正的外部异步工作注册 IdlingResource
IdlingResourcekotlin
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 (and the implicit inside every node query) will block until . MUST keep lightweight — it is called from the main thread ().
waitForIdlewaitForIdleisIdleNow == trueisIdleNowIdlingResource.kt:38-46kotlin
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)) }注册之后,每次 以及每次节点查询内部隐式执行的 ,都会阻塞到 为止。必须确保 足够轻量,因为它会在主线程中被调用()。
waitForIdlewaitForIdleisIdleNow == trueisIdleNowIdlingResource.kt:38-46Patterns
模式
Pattern: WRONG — Thread.sleep
to wait for a node
Thread.sleep模式:错误——使用 Thread.sleep
等待节点
Thread.sleepkotlin
// 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
waitUntil模式:错误——对可通过 Compose 状态观察到的条件使用 waitUntil
waitUntilkotlin
// 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()模式:hasPendingWork()
——被动检查,仅适用于暂停时钟
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 appliedFrom :
ComposeUiTest.kt:251-256IfisautoAdvance, the testing framework continuously processes pending work. In that scenario, calling this method acts as a momentary snapshot and will generally returntrue. It may briefly returnfalseif work is queued but the framework hasn't auto-advanced yet, making the result fleeting and unreliable for driving test logic.true
MUST NOT drive test logic off while .
hasPendingWork()autoAdvance == truekotlin
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 == truehasPendingWork()Pattern: lift the master idling timeout for slow CI
模式:为较慢的 CI 提高主 idle 超时
kotlin
@Before fun setUp() {
IdlingPolicies.setMasterPolicyTimeout(60, TimeUnit.SECONDS)
}Apply when (not ) times out on CI but passes locally. Both and honor this policy.
waitForIdlewaitUntilEspressoLinkRobolectricIdlingStrategykotlin
@Before fun setUp() {
IdlingPolicies.setMasterPolicyTimeout(60, TimeUnit.SECONDS)
}当 (而不是 )在 CI 上超时、但本地可以通过时,可以采用此方式。 和 都会遵循该策略。
waitForIdlewaitUntilEspressoLinkRobolectricIdlingStrategyMandatory rules
强制规则
- MUST prefer over
mainClock.advanceTimeUntil { state }whenever the awaited condition is a Compose-state read (skydoves hot take #4).rule.waitUntil { state } - MUST wrap state reads from the test thread in or
runOnIdle { … }. DirectrunOnUiThread { … }reads from the test thread race the recomposer (skydoves hot take #5).state.value - MUST call (not
runOnUiThread) for state mutations under a paused clock (runOnIdle);autoAdvance = false's implicitrunOnIdleis wrong for that mode. SeewaitForIdle.../testing-animations-deterministically/SKILL.md - MUST use for assert-only blocks that do many node reads — it suppresses the redundant per-query
runWhenIdle { … }. MUST NOT mutate state inside.waitForIdle - MUST prefer /
waitUntilExactlyOneExists/waitUntilAtLeastOneExistsover hand-rolledwaitUntilDoesNotExist. They are clearer and cite awaitUntil { onAllNodes(...).fetchSemanticsNodes().isNotEmpty() }in the timeout message.conditionDescription - MUST NOT treat as actionable while
hasPendingWork(). It is a passive snapshot; reliable only with the clock paused (autoAdvance == true).ComposeUiTest.kt:251-256 - MUST NOT use to wait for state to settle. Replace with
Thread.sleep,waitUntil*, or anmainClock.advanceTimeUntil(skydoves hot take #7). The one legitimateIdlingResourceis on the RenderThread for ripple/screenshot tests.Thread.sleep - PREFERRED: an per genuine external async source (HTTP, DB, an external counter), registered in
IdlingResourceand unregistered in@Before. Override@Afterso timeout messages are useful.getDiagnosticMessageIfBusy() - PREFERRED: in
IdlingPolicies.setMasterPolicyTimeout(...)for CI flakes due to slow agents — uniformly lifts both Espresso and Robolectric.@Before
- 只要等待条件是 Compose 状态读取,必须优先使用 ,而不是
mainClock.advanceTimeUntil { state }(Skydoves 热门观点 #4)。rule.waitUntil { state } - 必须将测试线程中的状态读取包装在 或
runOnIdle { … }中。直接从测试线程读取runOnUiThread { … }会与state.value产生竞态(Skydoves 热门观点 #5)。recomposer - 在暂停时钟()下修改状态时,必须调用
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(Skydoves 热门观点 #7)。唯一合理的IdlingResource场景是在 RenderThread 上执行波纹或截图测试。Thread.sleep - 首选: 为每个真正的外部异步源(HTTP、DB、外部计数器)注册一个 ,在
IdlingResource中注册,并在@Before中注销。重写@After,以便提供有用的超时消息。getDiagnosticMessageIfBusy() - 首选: 在 中调用
@Before,处理由 CI agent 过慢导致的测试不稳定;该设置会统一提高 Espresso 和 Robolectric 的超时时间。IdlingPolicies.setMasterPolicyTimeout(...)
Verification
验证
- No exists in any test method except the documented RenderThread/screenshot exceptions.
Thread.sleep - Every state read from the test thread is wrapped in (search:
runOnIdle { … }).grep -nP 'state\.\w+' src/androidTest - Every for a Compose-state condition has been migrated to
waitUntil { state.value … }.mainClock.advanceTimeUntil { state.value … } - Every "wait for node" path uses /
waitUntilExactlyOneExists/waitUntilAtLeastOneExistsrather than a hand-rolledwaitUntilDoesNotExistoverwaitUntil.fetchSemanticsNodes() - Every external async source has a registered , registered in
IdlingResourceand unregistered in@Before.@After - No call site relies on while
hasPendingWork().autoAdvance == true - CI run completes 50 iterations without an or
AndroidComposeUiTestTimeoutExceptionflake.ComposeTimeoutException
- 除已记录的 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 reference: https://developer.android.com/reference/androidx/test/espresso/IdlingPolicies
IdlingPolicies - —
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/ComposeUiTest.kt:174-260,waitForIdle,awaitIdle,waitUntil,runOnIdle,runOnUiThread,runWhenIdle,awaitAndRunWhenIdle.hasPendingWork - — the experimental
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/ComposeUiTest.kt:275-335/waitUntilNodeCount/waitUntilExactlyOneExists/waitUntilAtLeastOneExistsextensions.waitUntilDoesNotExist - — the public
compose/ui/ui-test/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/IdlingResource.ktinterface.IdlingResource - — the registry that aggregates user-registered resources + Compose's own.
compose/ui/ui-test/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/IdlingResourceRegistry.jvmAndAndroid.kt - — Compose's automatically-registered resource; 100-frame cap at line 109.
compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeIdlingResource.android.kt - — the
compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/EspressoLink.android.ktbridge.androidx.test.espresso.IdlingResource - —
compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeUiTest.android.kt:885-908's 10 ms wall-clock poll loop.waitUntil - —
compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/AndroidSynchronization.android.ktposts arunOnUiThreadviaFutureTask.Instrumentation.runOnMainSync - — canonical
compose/material3/material3/src/androidDeviceTest/kotlin/androidx/compose/material3/SnackbarHostTest.kt:77-88.rule.waitUntil { job.isCompleted } - Sibling skill: —
../controlling-the-test-clock/SKILL.md, frame model,MainTestClock.advanceTimeUntil - Sibling skill: — paused-clock animation tests.
../testing-animations-deterministically/SKILL.md - Sibling skill: — JUnit lifecycle around idle waits.
../../patterns/structuring-a-compose-test/SKILL.md - Sibling skill: — when "node not found" turns out to be a finder issue, not an async issue.
../../debug/printing-the-semantics-tree/SKILL.md
- Android Developers——Compose 测试:https://developer.android.com/develop/ui/compose/testing
- Android Developers——Compose 测试速查表:https://developer.android.com/develop/ui/compose/testing-cheatsheet
- Espresso 参考:https://developer.android.com/reference/androidx/test/espresso/IdlingPolicies
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 自身资源的 registry。
compose/ui/ui-test/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/IdlingResourceRegistry.jvmAndAndroid.kt - ——Compose 自动注册的资源;第 109 行包含 100 帧上限。
compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeIdlingResource.android.kt - ——
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的 10 ms 墙钟时间轮询循环。waitUntil - ——
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:——围绕 idle 等待组织 JUnit 生命周期。
../../patterns/structuring-a-compose-test/SKILL.md - 同级 skill:——当“node not found”实际是 finder 问题时使用。
../../debug/printing-the-semantics-tree/SKILL.md