controlling-the-test-clock

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Controlling the Test Clock — Frames, Time, and the Recomposer

控制测试时钟——帧、时间与 Recomposer

MainTestClock
is the only knob that drives recomposition, animations, and
LaunchedEffect
s in a Compose test. This skill explains its surface, the 16 ms frame model behind it, and how
autoAdvance
flips the test from "framework drives the clock" to "the test drives the clock". The animation recipe and the idle/wait recipe live in sibling skills — this one establishes the mechanics they both depend on.
MainTestClock
是 Compose 测试中唯一用于驱动重组、动画和
LaunchedEffect
的控制项。本 skill 介绍它的 API、背后的 16 ms 帧模型,以及
autoAdvance
如何将测试从“框架驱动时钟”切换为“测试驱动时钟”。动画配方和 idle/wait 配方位于同级 skill;本 skill 讲解二者共同依赖的底层机制。

When to use this skill

何时使用此 skill

  • The developer asks what
    mainClock.advanceTimeBy(...)
    actually does, why it rounds up, or why the animation seems off by one frame.
  • The developer is migrating from
    androidx.compose.ui.test.junit4.createComposeRule
    (v1) to
    androidx.compose.ui.test.junit4.v2.createComposeRule
    (v2) and tests now require an explicit
    mainClock.runCurrent()
    or
    advanceTimeBy(0)
    .
  • The developer mentions
    MainTestClock
    ,
    TestCoroutineScheduler
    ,
    TestMonotonicFrameClock
    ,
    ComposeTimeoutException
    ,
    advanceTimeUntil
    , or "test clock vs wall clock".
  • The developer is writing a test that needs a particular frame count and is unsure whether
    advanceTimeBy(5)
    produces zero, one, or many frames.
  • The developer asks why the animation's
    playTime
    is still
    0
    after one frame.
  • 开发者询问
    mainClock.advanceTimeBy(...)
    实际做了什么、为什么会向上取整,或者为什么动画看起来差了一帧。
  • 开发者正在从
    androidx.compose.ui.test.junit4.createComposeRule
    (v1)迁移到
    androidx.compose.ui.test.junit4.v2.createComposeRule
    (v2),而测试现在需要显式调用
    mainClock.runCurrent()
    或
    advanceTimeBy(0)
    。
  • 开发者提及
    MainTestClock
    、
    TestCoroutineScheduler
    、
    TestMonotonicFrameClock
    、
    ComposeTimeoutException
    、
    advanceTimeUntil
    或 test clock vs wall clock。
  • 开发者编写的测试需要特定的帧数,但不确定
    advanceTimeBy(5)
    会产生零帧、一帧还是多帧。
  • 开发者询问为什么动画经过一帧后,其
    playTime
    仍然是
    0
    。

When NOT to use this skill

何时不应使用此 skill

  • The goal is a deterministic animation test (the
    autoAdvance = false
    recipe). Use
    ../testing-animations-deterministically/SKILL.md
    .
  • The goal is to wait on
    IdlingResource
    s, async work, or "the UI is settled". Use
    ../synchronizing-with-idle/SKILL.md
    .
  • The goal is the higher-level test structure (rule wiring,
    setContent
    , JUnit lifecycle). Use
    ../../patterns/structuring-a-compose-test/SKILL.md
    .
  • The goal is choosing between
    createComposeRule
    and
    runComposeUiTest
    . Use
    ../../setup/choosing-test-rule-vs-runtest/SKILL.md
    .
  • 目标是编写确定性的动画测试(
    autoAdvance = false
    配方)。请使用
    ../testing-animations-deterministically/SKILL.md
    。
  • 目标是等待
    IdlingResource
    、异步工作或“UI 已稳定”。请使用
    ../synchronizing-with-idle/SKILL.md
    。
  • 目标是处理更高层的测试结构(rule 配置、
    setContent
    、JUnit 生命周期)。请使用
    ../../patterns/structuring-a-compose-test/SKILL.md
    。
  • 目标是在
    createComposeRule
    与
    runComposeUiTest
    之间做选择。请使用
    ../../setup/choosing-test-rule-vs-runtest/SKILL.md
    。

Prerequisites

前置条件

  • androidx.compose.ui:ui-test
    and
    androidx.compose.ui:ui-test-junit4
    (or the JUnit-less
    runComposeUiTest
    ) on the test source set.
  • A
    ComposeContentTestRule
    from
    createComposeRule()
    or a
    ComposeUiTest
    receiver from
    runComposeUiTest { … }
    .
  • PREFERRED: the v2 entry points (
    androidx.compose.ui.test.junit4.v2.createComposeRule
    ,
    androidx.compose.ui.test.v2.runComposeUiTest
    ). The v1 forms are
    @Deprecated(level = WARNING)
    (skydoves hot take #6).
  • 测试 source set 中包含
    androidx.compose.ui:ui-test
    和
    androidx.compose.ui:ui-test-junit4
    (或不含 JUnit 的
    runComposeUiTest
    )。
  • 拥有来自
    createComposeRule()
    的
    ComposeContentTestRule
    ,或来自
    runComposeUiTest { … }
    的
    ComposeUiTest
    receiver。
  • **推荐:**使用 v2 入口点(
    androidx.compose.ui.test.junit4.v2.createComposeRule
    、
    androidx.compose.ui.test.v2.runComposeUiTest
    )。v1 形式已被弃用,级别为
    WARNING
    (skydoves 的个人观点 #6)。

The mental model

心智模型

MainTestClock
is not a
MonotonicFrameClock
— it is an interface whose advance methods drive a
kotlinx.coroutines.test.TestCoroutineScheduler
. The recomposer reads frames from a
TestMonotonicFrameClock
whose
withFrameNanos
is implemented by
delay(frameDelayMillis)
against the same scheduler (
TestMonotonicFrameClock.jvmAndAndroid.kt:105-117
). Advancing the scheduler causes the
delay
to fire, which causes a frame to be produced, which runs
onPerformTraversals
and triggers measure+layout on each compose root.
MainTestClock.advanceTimeBy(ms)
        │
        ▼  AbstractMainTestClock.advanceScheduler
TestCoroutineScheduler.advanceTimeBy(ms) → runCurrent()
        │
        ▼  delay(frameDelayMillis) inside TestMonotonicFrameClock fires
performFrame()  ── awaiters (withFrameNanos) resume FIRST
        │       ── then onPerformTraversals → recomposition → measure/layout
        ▼
Recomposer applies snapshot writes
This is why
autoAdvance = false
is enough to freeze the entire UI: nothing else ticks the scheduler unless an explicit
mainClock.advance*
call is made (
MainTestClock.kt:43-48
KDoc).
MainTestClock
不是
MonotonicFrameClock
——它是一个接口,其推进方法会驱动
kotlinx.coroutines.test.TestCoroutineScheduler
。Recomposer 从
TestMonotonicFrameClock
读取帧,而该时钟的
withFrameNanos
是针对同一个 scheduler 通过
delay(frameDelayMillis)
实现的(
TestMonotonicFrameClock.jvmAndAndroid.kt:105-117
)。推进 scheduler 会触发
delay
,进而产生一帧,随后执行
onPerformTraversals
,并在每个 Compose root 上触发 measure 和 layout。
MainTestClock.advanceTimeBy(ms)
        │
        ▼  AbstractMainTestClock.advanceScheduler
TestCoroutineScheduler.advanceTimeBy(ms) → runCurrent()
        │
        ▼  delay(frameDelayMillis) inside TestMonotonicFrameClock fires
performFrame()  ── awaiters (withFrameNanos) resume FIRST
        │       ── then onPerformTraversals → recomposition → measure/layout
        ▼
Recomposer applies snapshot writes
这就是为什么仅设置
autoAdvance = false
就足以冻结整个 UI:除非显式调用
mainClock.advance*
,否则不会有其他机制推动 scheduler 前进(
MainTestClock.kt:43-48
KDoc)。

The MainTestClock surface

MainTestClock API

Every entry comes from
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/MainTestClock.kt
.
MemberBehavior
currentTime: Long
Test clock time in milliseconds. NOT wall clock. Reads
scheduler.currentTime
(
AbstractMainTestClock.kt:35-36
).
scheduler: TestCoroutineScheduler
The scheduler the recomposer and clock share. Useful for
runCurrent()
from outside (
MainTestClock.kt:84-99
).
autoAdvance: Boolean
Default
true
. When
true
, framework auto-advances the clock during
waitForIdle
/
waitUntil
. When
false
, only explicit
advanceTime*
calls move the clock (
MainTestClock.kt:101-115
).
advanceTimeByFrame()
Advances by exactly one frame (16 ms on Android/Desktop). Implemented as
advanceScheduler(frameDelayMillis)
(
AbstractMainTestClock.kt:40-42
).
advanceTimeBy(milliseconds, ignoreFrameDuration = false)
Rounds up to the nearest multiple of frame duration unless
ignoreFrameDuration = true
(
AbstractMainTestClock.kt:44-52
,
MainTestClock.kt:120-145
).
advanceTimeUntil(timeoutMillis = 1_000, condition)
Advances frame-by-frame until
condition()
is true. Timeout is test clock. Throws
ComposeTimeoutException
(
MainTestClock.kt:147-167
,
AbstractMainTestClock.kt:54-72
).
runCurrent()
is exposed on
AbstractMainTestClock
(
AbstractMainTestClock.kt:96-98
) — it executes all tasks due at the current time without advancing the clock. Reach for it after toggling state in v2 if a queued task must run before the next assertion.
每个入口都来自
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/MainTestClock.kt
。
成员行为
currentTime: Long
以毫秒为单位的测试时钟时间。不是实际时间。读取
scheduler.currentTime
(
AbstractMainTestClock.kt:35-36
)。
scheduler: TestCoroutineScheduler
Recomposer 与时钟共享的 scheduler。可用于从外部调用
runCurrent()
(
MainTestClock.kt:84-99
)。
autoAdvance: Boolean
默认为
true
。为
true
时,框架会在
waitForIdle
/
waitUntil
期间自动推进时钟;为
false
时,只有显式调用
advanceTime*
才会推动时钟(
MainTestClock.kt:101-115
)。
advanceTimeByFrame()
精确推进一帧(Android/Desktop 上为 16 ms)。通过
advanceScheduler(frameDelayMillis)
实现(
AbstractMainTestClock.kt:40-42
)。
advanceTimeBy(milliseconds, ignoreFrameDuration = false)
除非设置
ignoreFrameDuration = true
,否则会向上取整到最接近的帧时长倍数(
AbstractMainTestClock.kt:44-52
、
MainTestClock.kt:120-145
)。
advanceTimeUntil(timeoutMillis = 1_000, condition)
逐帧推进,直到
condition()
返回 true。超时基于测试时钟。抛出
ComposeTimeoutException
(
MainTestClock.kt:147-167
、
AbstractMainTestClock.kt:54-72
)。
runCurrent()
在
AbstractMainTestClock
上公开(
AbstractMainTestClock.kt:96-98
)——它会在不推进时钟的情况下执行当前时间已到期的全部任务。在 v2 中切换状态后,如果必须在下一次断言前运行已排队的任务,应调用此方法。

The frame model

帧模型

  • Frame duration:
    DefaultFrameDelay = 16_000_000L
    ns = 16 ms (
    TestMonotonicFrameClock.jvmAndAndroid.kt:33
    ).
  • Per-frame order inside
    performFrame
    :
    1. All
      withFrameNanos
      awaiters resume with the new frame time. Animations live here.
    2. onPerformTraversals
      runs — composition + measure + layout.
    3. Resumptions queued by the awaiters are dispatched.
Quoted from
MainTestClock.kt:49-60
:
If there is both a pending recomposition and an animation awaiting a frame time, ticking this clock will first send the new frame time to the animation, and then perform recomposition. … Because animations receive their frame time before recomposition, an animation will not get its start time in the first frame after kicking it off by toggling a state variable.
That last sentence is the reason every animation test does an extra
advanceTimeByFrame()
immediately after
setContent
to "kick off" the animation: the toggle frame schedules the animation; the next frame initializes its play time to
0
(skydoves hot take #3).
  • 帧时长:
    DefaultFrameDelay = 16_000_000L
    ns,即 16 ms(
    TestMonotonicFrameClock.jvmAndAndroid.kt:33
    )。
  • performFrame
    内的每帧顺序:
    1. 所有
      withFrameNanos
      等待者使用新的帧时间恢复执行。动画位于此处。
    2. 执行
      onPerformTraversals
      ——composition、measure 和 layout。
    3. 调度由等待者触发的恢复执行。
引用自
MainTestClock.kt:49-60
:
如果同时存在待处理的重组和等待帧时间的动画,tick 此时钟会_首先_将新的帧时间发送给动画,_然后_执行重组。……由于动画在重组_之前_收到帧时间,因此通过切换状态变量启动动画后的第一帧中,动画不会获得其开始时间。
最后一句正是每个动画测试都要在
setContent
后立即额外调用一次
advanceTimeByFrame()
来“启动”动画的原因:切换状态的帧只会调度动画;下一帧会将动画的 play time 初始化为
0
(skydoves 的个人观点 #3)。

Workflow

工作流

1. Read
currentTime
only as a witness, never as a synchronization mechanism

1. 仅将
currentTime
作为校验依据读取,绝不将其用作同步机制

kotlin
// RIGHT — assert the clock advanced as much as the test asked
val before = rule.mainClock.currentTime
rule.mainClock.advanceTimeBy(durationMillis = 320)
assertEquals(320, rule.mainClock.currentTime - before)
kotlin
// WRONG
while (rule.mainClock.currentTime < target) { /* spin */ }
// WRONG because: nothing in this loop drives the scheduler. The loop runs forever.
kotlin
// RIGHT — assert the clock advanced as much as the test asked
val before = rule.mainClock.currentTime
rule.mainClock.advanceTimeBy(durationMillis = 320)
assertEquals(320, rule.mainClock.currentTime - before)
kotlin
// WRONG
while (rule.mainClock.currentTime < target) { /* spin */ }
// WRONG because: nothing in this loop drives the scheduler. The loop runs forever.

2. Choose the right advance method

2. 选择正确的推进方法

GoalCall
"Run exactly one frame."
mainClock.advanceTimeByFrame()
"Run N frames."
mainClock.advanceTimeBy(N * 16L)
"Run a known animation duration."
mainClock.advanceTimeBy(durationMillis = 300)
(rounded up to next 16 ms boundary)
"Step time without producing a new frame."
mainClock.advanceTimeBy(milliseconds = 8, ignoreFrameDuration = true)
"Wait until a Compose state condition becomes true."
mainClock.advanceTimeUntil(timeoutMillis = 5_000) { state.value == … }
目标调用
“恰好运行一帧。”
mainClock.advanceTimeByFrame()
“运行 N 帧。”
mainClock.advanceTimeBy(N * 16L)
“运行一段已知时长的动画。”
mainClock.advanceTimeBy(durationMillis = 300)
(向上取整到下一个 16 ms 边界)
“推进时间但不产生新帧。”
mainClock.advanceTimeBy(milliseconds = 8, ignoreFrameDuration = true)
“等待某个 Compose 状态条件变为 true。”
mainClock.advanceTimeUntil(timeoutMillis = 5_000) { state.value == … }

3. After mutating state under v2, run pending tasks before asserting

3. 在 v2 中修改状态后,先运行待处理任务再断言

The v2
createComposeRule
uses a
StandardTestDispatcher
for composition; tasks are queued, not executed immediately. If
autoAdvance = false
, neither
waitForIdle
nor a node query will drain those tasks. The fix is
mainClock.runCurrent()
or
mainClock.advanceTimeBy(0)
:
kotlin
rule.mainClock.autoAdvance = false
rule.runOnUiThread { uiState = newValue }
// Under v2, the snapshot write is queued. Drain it before asserting.
rule.mainClock.advanceTimeByFrame()
rule.onNodeWithTag("status").assertTextEquals("Updated")
AbstractMainTestClock.advanceTimeUntil
already calls
scheduler.runCurrent()
first when
isStandardTestDispatcherSupportEnabled
is true (
AbstractMainTestClock.kt:59-61
).
v2 的
createComposeRule
使用
StandardTestDispatcher
执行 composition;任务会被排队,而不是立即执行。如果
autoAdvance = false
,那么
waitForIdle
和节点查询都不会清空这些任务。解决方法是调用
mainClock.runCurrent()
或
mainClock.advanceTimeBy(0)
:
kotlin
rule.mainClock.autoAdvance = false
rule.runOnUiThread { uiState = newValue }
// Under v2, the snapshot write is queued. Drain it before asserting.
rule.mainClock.advanceTimeByFrame()
rule.onNodeWithTag("status").assertTextEquals("Updated")
当
isStandardTestDispatcherSupportEnabled
为 true 时,
AbstractMainTestClock.advanceTimeUntil
已经首先调用
scheduler.runCurrent()
(
AbstractMainTestClock.kt:59-61
)。

4. Treat
ComposeTimeoutException
as a verdict on the condition, not on the clock

4. 将
ComposeTimeoutException
视为对条件而非时钟的判定

advanceTimeUntil
throws
ComposeTimeoutException("Condition still not satisfied after $timeoutMillis ms")
when the test clock advances past
timeoutMillis
without
condition()
returning
true
(
AbstractMainTestClock.kt:65-68
). The exception means the condition will never be satisfied by clock-driven work — typically a missing snapshot write, a
LaunchedEffect
that never starts, or a state read on the wrong thread.
当测试时钟推进超过
timeoutMillis
,但
condition()
仍未返回 true 时,
advanceTimeUntil
会抛出
ComposeTimeoutException("Condition still not satisfied after $timeoutMillis ms")
(
AbstractMainTestClock.kt:65-68
)。该异常意味着仅靠时钟驱动的工作永远无法满足条件——通常是因为缺少 snapshot write、
LaunchedEffect
未能启动,或在错误的线程上读取了状态。

Patterns

模式

Pattern: rounding up

模式:向上取整

kotlin
// WRONG
rule.mainClock.advanceTimeBy(milliseconds = 5)
// expectation: "1 frame ran"
// WRONG because: the framework rounds 5 ms UP to the next 16 ms multiple — i.e. 16 ms.
// One frame did run, but the developer is reading the API as if it could advance by 5 ms.
// Use ignoreFrameDuration = true if sub-frame stepping is genuinely required.
kotlin
// RIGHT
rule.mainClock.advanceTimeByFrame()             // exactly 16 ms, exactly one frame
// or
rule.mainClock.advanceTimeBy(milliseconds = 5, ignoreFrameDuration = true)  // 5 ms, 0 frames
kotlin
// WRONG
rule.mainClock.advanceTimeBy(milliseconds = 5)
// expectation: "1 frame ran"
// WRONG because: the framework rounds 5 ms UP to the next 16 ms multiple — i.e. 16 ms.
// One frame did run, but the developer is reading the API as if it could advance by 5 ms.
// Use ignoreFrameDuration = true if sub-frame stepping is genuinely required.
kotlin
// RIGHT
rule.mainClock.advanceTimeByFrame()             // exactly 16 ms, exactly one frame
// or
rule.mainClock.advanceTimeBy(milliseconds = 5, ignoreFrameDuration = true)  // 5 ms, 0 frames

Pattern: the "kick-off" frame for animations

模式:动画的“启动帧”

kotlin
// WRONG
rule.mainClock.autoAdvance = false
rule.setContent { Crossfade(showFirst) { /* … */ } }
rule.mainClock.advanceTimeBy(300)                  // expect animation finished
rule.onNodeWithText("Second").assertExists()
// WRONG because: the toggle frame only schedules the animation; the animation's playTime is 0
// going into the next frame. The first 16 ms of the 300 are eaten by setup.
kotlin
// RIGHT — see CrossfadeTest.kt:70-93
rule.mainClock.autoAdvance = false
rule.setContent { Crossfade(showFirst) { /* … */ } }
rule.mainClock.advanceTimeByFrame()                // kick off
rule.mainClock.advanceTimeBy(durationMillis = 300) // step
rule.onNodeWithText("Second").assertExists()
kotlin
// WRONG
rule.mainClock.autoAdvance = false
rule.setContent { Crossfade(showFirst) { /* … */ } }
rule.mainClock.advanceTimeBy(300)                  // expect animation finished
rule.onNodeWithText("Second").assertExists()
// WRONG because: the toggle frame only schedules the animation; the animation's playTime is 0
// going into the next frame. The first 16 ms of the 300 are eaten by setup.
kotlin
// RIGHT — see CrossfadeTest.kt:70-93
rule.mainClock.autoAdvance = false
rule.setContent { Crossfade(showFirst) { /* … */ } }
rule.mainClock.advanceTimeByFrame()                // kick off
rule.mainClock.advanceTimeBy(durationMillis = 300) // step
rule.onNodeWithText("Second").assertExists()

Pattern: v1 → v2 migration leaves a state read stale

模式:v1 → v2 迁移后状态读取仍然陈旧

kotlin
// WRONG (v2)
val rule = androidx.compose.ui.test.junit4.v2.createComposeRule()
@Test fun foo() {
    var counter by mutableStateOf(0)
    rule.setContent { Text(counter.toString()) }
    rule.runOnUiThread { counter = 1 }
    rule.onNodeWithText("1").assertExists()
    // WRONG because: with StandardTestDispatcher, the snapshot apply is queued.
    // No frame has been produced. The composition still reads `0`.
}
kotlin
// RIGHT (v2)
@Test fun foo() {
    var counter by mutableStateOf(0)
    rule.setContent { Text(counter.toString()) }
    rule.runOnUiThread { counter = 1 }
    rule.mainClock.advanceTimeByFrame()
    rule.onNodeWithText("1").assertExists()
}
kotlin
// WRONG (v2)
val rule = androidx.compose.ui.test.junit4.v2.createComposeRule()
@Test fun foo() {
    var counter by mutableStateOf(0)
    rule.setContent { Text(counter.toString()) }
    rule.runOnUiThread { counter = 1 }
    rule.onNodeWithText("1").assertExists()
    // WRONG because: with StandardTestDispatcher, the snapshot apply is queued.
    // No frame has been produced. The composition still reads `0`.
}
kotlin
// RIGHT (v2)
@Test fun foo() {
    var counter by mutableStateOf(0)
    rule.setContent { Text(counter.toString()) }
    rule.runOnUiThread { counter = 1 }
    rule.mainClock.advanceTimeByFrame()
    rule.onNodeWithText("1").assertExists()
}

Pattern:
advanceTimeUntil
saves wall time

模式:
advanceTimeUntil
节省实际耗时

kotlin
// LESS PREFERRED — wall clock
rule.waitUntil(timeoutMillis = 5_000) { state.value == Phase.Done }
kotlin
// PREFERRED — test clock; framework iterates frame-by-frame and the timeout is in
// test clock time (no real wall-clock burn between iterations).
rule.mainClock.advanceTimeUntil(timeoutMillis = 5_000) { state.value == Phase.Done }
Both variants advance the test clock when
autoAdvance == true
:
waitUntil
calls
mainClock.advanceTimeByFrame()
AND
Thread.sleep(10)
per iteration (
ComposeUiTest.android.kt:899-902
);
advanceTimeUntil
only advances the test clock by frames (
AbstractMainTestClock.kt:54-72
). The difference is the timeout source — wall vs test — and the absence of
Thread.sleep
overhead in the test-clock variant.
kotlin
// LESS PREFERRED — wall clock
rule.waitUntil(timeoutMillis = 5_000) { state.value == Phase.Done }
kotlin
// PREFERRED — test clock; framework iterates frame-by-frame and the timeout is in
// test clock time (no real wall-clock burn between iterations).
rule.mainClock.advanceTimeUntil(timeoutMillis = 5_000) { state.value == Phase.Done }
当
autoAdvance == true
时,两个变体都会推进测试时钟:
waitUntil
每次迭代都会调用
mainClock.advanceTimeByFrame()
并执行
Thread.sleep(10)
(
ComposeUiTest.android.kt:899-902
);
advanceTimeUntil
只会按帧推进测试时钟(
AbstractMainTestClock.kt:54-72
)。二者的区别在于超时时间来源——实际时间与测试时间——以及测试时钟变体不存在
Thread.sleep
开销。

Mandatory rules

强制规则

  • MUST treat
    MainTestClock.currentTime
    as test clock time only. Comparing it to
    System.currentTimeMillis()
    is meaningless.
  • MUST call
    advanceTimeByFrame()
    (not
    advanceTimeBy(16)
    ) when the intent is "exactly one frame." It documents intent and avoids reasoning about rounding.
  • MUST know that
    advanceTimeBy(milliseconds = N)
    rounds up to the next multiple of
    frameDelayMillis
    (16 ms on Android/Desktop). Pass
    ignoreFrameDuration = true
    to suppress rounding (
    AbstractMainTestClock.kt:44-52
    ).
  • MUST call
    advanceTimeByFrame()
    (or
    advanceTimeBy(0)
    /
    runCurrent()
    ) after toggling state under v2 (
    StandardTestDispatcher
    ) before reading the resulting UI state. v1's
    UnconfinedTestDispatcher
    dispatches eagerly and does not need this; v2 does (skydoves hot take #6).
  • MUST NOT use
    advanceTimeUntil
    for conditions outside Compose's snapshot system (e.g. a
    Job.isCompleted
    , an
    OkHttp
    callback). Those conditions will never become true by ticking the test clock —
    waitUntil
    (wall clock) or an
    IdlingResource
    is the right tool. See
    ../synchronizing-with-idle/SKILL.md
    .
  • MUST NOT confuse
    MainTestClock
    with
    MonotonicFrameClock
    . They are different types.
    MainTestClock
    exposes the scheduler that drives the
    TestMonotonicFrameClock
    the recomposer uses.
  • PREFERRED: the v2 entry points so the dispatcher matches
    kotlinx.coroutines.test.runTest
    semantics. The v1
    createComposeRule
    /
    runComposeUiTest
    forms are deprecated
    WARNING
    .
  • PREFERRED:
    advanceTimeUntil
    over
    waitUntil
    whenever the awaited condition is observable through Compose state. Test clock is faster and deterministic; wall clock sleeps 10 ms per iteration.
  • 必须将
    MainTestClock.currentTime
    仅视为测试时钟时间。将其与
    System.currentTimeMillis()
    比较毫无意义。
  • 必须在意图为“恰好一帧”时调用
    advanceTimeByFrame()
    (而不是
    advanceTimeBy(16)
    )。这样可以明确表达意图,并避免考虑取整规则。
  • 必须了解
    advanceTimeBy(milliseconds = N)
    会向上取整到下一个
    frameDelayMillis
    倍数(Android/Desktop 上为 16 ms)。传入
    ignoreFrameDuration = true
    可禁止取整(
    AbstractMainTestClock.kt:44-52
    )。
  • 必须在 v2(
    StandardTestDispatcher
    )下切换状态后,调用
    advanceTimeByFrame()
    (或
    advanceTimeBy(0)
    /
    runCurrent()
    ),然后再读取生成的 UI 状态。v1 的
    UnconfinedTestDispatcher
    会立即调度,因此不需要这样做;v2 需要(skydoves 的个人观点 #6)。
  • 不得将
    advanceTimeUntil
    用于 Compose snapshot 系统之外的条件(例如
    Job.isCompleted
    、
    OkHttp
    callback)。仅通过 tick 测试时钟,这些条件永远不会变为 true——应使用
    waitUntil
    (实际时间)或
    IdlingResource
    。请参阅
    ../synchronizing-with-idle/SKILL.md
    。
  • 不得混淆
    MainTestClock
    与
    MonotonicFrameClock
    。它们是不同类型。
    MainTestClock
    公开 scheduler,由该 scheduler 驱动 Recomposer 使用的
    TestMonotonicFrameClock
    。
  • **推荐:**使用 v2 入口点,使 dispatcher 与
    kotlinx.coroutines.test.runTest
    的语义保持一致。v1 的
    createComposeRule
    /
    runComposeUiTest
    形式已被弃用,级别为
    WARNING
    。
  • **推荐:**只要等待条件能够通过 Compose 状态观测,就优先使用
    advanceTimeUntil
    而不是
    waitUntil
    。测试时钟更快且具有确定性;实际时间变体每次迭代都会休眠 10 ms。

Verification

验证

  • Every call site uses
    advanceTimeByFrame()
    for "one frame" and
    advanceTimeBy(...)
    only when the duration is meaningful.
  • No
    advanceTimeBy(milliseconds = X)
    where
    X < 16
    exists without a comment explaining the intent or an
    ignoreFrameDuration = true
    flag.
  • After v1 → v2 migration, every state mutation followed by an assertion either calls
    mainClock.advanceTimeByFrame()
    /
    advanceTimeBy(0)
    /
    runCurrent()
    or relies on
    runOnIdle { … }
    to drain queued tasks.
  • advanceTimeUntil
    sites read Compose state only — no
    Job.isCompleted
    , no external counters.
  • ComposeTimeoutException
    from a clock test is treated as a missing snapshot write or wrong-thread state read, not a "raise the timeout" event.
  • 每个调用点在需要“运行一帧”时都使用
    advanceTimeByFrame()
    ,仅在时长具有实际意义时使用
    advanceTimeBy(...)
    。
  • 不存在未附意图说明或
    ignoreFrameDuration = true
    标志的
    advanceTimeBy(milliseconds = X)
    ,其中
    X < 16
    。
  • 从 v1 迁移到 v2 后,每次状态修改后的断言之前,都会调用
    mainClock.advanceTimeByFrame()
    /
    advanceTimeBy(0)
    /
    runCurrent()
    ,或依赖
    runOnIdle { … }
    清空已排队的任务。
  • advanceTimeUntil
    的调用点只读取 Compose 状态——不读取
    Job.isCompleted
    或外部计数器。
  • 将时钟测试中的
    ComposeTimeoutException
    视为缺少 snapshot write 或错误线程状态读取,而不是“应该提高超时时间”的事件。

References

参考资料

  • Android Developers — Compose testing: https://developer.android.com/develop/ui/compose/testing
  • Android Developers — Testing animations: https://developer.android.com/develop/ui/compose/animation/testing
  • Compose UI release notes: https://developer.android.com/jetpack/androidx/releases/compose-ui
  • compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/MainTestClock.kt
    — the public interface and
    ComposeTimeoutException
    .
  • compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/AbstractMainTestClock.kt
    — the rounding rule,
    runCurrent
    ,
    advanceScheduler
    .
  • compose/ui/ui-test/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/TestMonotonicFrameClock.jvmAndAndroid.kt
    —
    DefaultFrameDelay = 16_000_000L
    , the
    delay
    -based frame loop.
  • compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/MainTestClockImpl.android.kt
    — the Android actual.
  • compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeUiTest.android.kt
    —
    waitUntil
    's 10 ms wall-clock sleep at line 885-905.
  • Sibling skill:
    ../testing-animations-deterministically/SKILL.md
    — the full
    autoAdvance = false
    recipe.
  • Sibling skill:
    ../synchronizing-with-idle/SKILL.md
    — choosing between
    waitForIdle
    ,
    waitUntil
    , and
    advanceTimeUntil
    .
  • Android Developers——Compose 测试:https://developer.android.com/develop/ui/compose/testing
  • Android Developers——动画测试:https://developer.android.com/develop/ui/compose/animation/testing
  • Compose UI 发行说明:https://developer.android.com/jetpack/androidx/releases/compose-ui
  • compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/MainTestClock.kt
    ——公共接口和
    ComposeTimeoutException
    。
  • compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/AbstractMainTestClock.kt
    ——取整规则、
    runCurrent
    、
    advanceScheduler
    。
  • compose/ui/ui-test/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/TestMonotonicFrameClock.jvmAndAndroid.kt
    ——
    DefaultFrameDelay = 16_000_000L
    和基于
    delay
    的帧循环。
  • compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/MainTestClockImpl.android.kt
    ——Android actual。
  • compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeUiTest.android.kt
    ——第 885-905 行中
    waitUntil
    的 10 ms 实际时间休眠。
  • 同级 skill:
    ../testing-animations-deterministically/SKILL.md
    ——完整的
    autoAdvance = false
    配方。
  • 同级 skill:
    ../synchronizing-with-idle/SKILL.md
    ——如何在
    waitForIdle
    、
    waitUntil
    和
    advanceTimeUntil
    之间选择。