structuring-a-compose-test

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Structuring a Compose Test — The androidx-Canonical Class Skeleton

组织 Compose 测试——androidx 标准类骨架

Compose tests fail or rot because their structure is wrong, not because the assertions are wrong. State that lives inside
setContent { }
cannot be driven from the test thread;
setContent
called inside
@Before
becomes a hidden race; combining
@get:Rule
with
runComposeUiTest { }
creates two competing test environments. This skill encodes the exact class skeleton used by
androidx.compose.material3
and
androidx.compose.foundation
so the developer's tests behave the same way.
Compose 测试失败或逐渐失效,通常是因为其结构有误,而不是断言有误。位于
setContent { }
内部的状态无法从测试线程驱动;在
@Before
中调用
setContent
会形成隐蔽的竞态;将
@get:Rule
与
runComposeUiTest { }
混用会创建两个相互竞争的测试环境。本 skill 固化了
androidx.compose.material3
和
androidx.compose.foundation
所使用的精确类骨架,使开发者的测试行为保持一致。

When to use this skill

何时使用此 skill

  • The developer is creating a new
    *Test.kt
    and asks where to put state, the rule, and
    setContent
    .
  • A test compiles but cannot mutate state mid-test ("how do I flip the checkbox after the first assertion?").
  • The developer pasted
    setContent
    into
    @Before
    and the test is now flaky or will not start.
  • A reviewer flags a test for declaring state inside
    setContent { }
    .
  • The developer mixed
    @get:Rule createComposeRule()
    and
    runComposeUiTest { }
    and gets confusing failures.
  • 开发者正在创建新的
    *Test.kt
    ,并询问状态、rule 和
    setContent
    应放在哪里。
  • 测试可以编译,但无法在测试中途修改状态(“第一次断言后如何切换复选框?”)。
  • 开发者将
    setContent
    放入
    @Before
    ,导致测试变得不稳定或无法启动。
  • 审查者指出测试在
    setContent { }
    内部声明了状态。
  • 开发者混用
    @get:Rule createComposeRule()
    和
    runComposeUiTest { }
    ,得到令人困惑的失败结果。

When NOT to use this skill

何时不应使用此 skill

  • The developer is choosing which entry point to use (rule vs.
    runComposeUiTest
    ); use
    ../../setup/choosing-test-rule-vs-runtest/SKILL.md
    .
  • The build cannot resolve
    createComposeRule
    ; use
    ../../setup/configuring-test-dependencies/SKILL.md
    .
  • The decision is host (Robolectric) vs. device (instrumentation); use
    ../../setup/setting-up-host-vs-device-tests/SKILL.md
    .
  • The test is specifically for a
    LazyColumn
    /
    LazyRow
    ; layer
    ../testing-lazy-lists/SKILL.md
    on top of this skeleton.
  • 开发者正在选择使用哪个入口(rule 与
    runComposeUiTest
    );请使用
    ../../setup/choosing-test-rule-vs-runtest/SKILL.md
    。
  • 构建无法解析
    createComposeRule
    ;请使用
    ../../setup/configuring-test-dependencies/SKILL.md
    。
  • 正在决定使用 host(Robolectric)还是 device(instrumentation);请使用
    ../../setup/setting-up-host-vs-device-tests/SKILL.md
    。
  • 测试专门针对
    LazyColumn
    /
    LazyRow
    ;请在此骨架上叠加
    ../testing-lazy-lists/SKILL.md
    。

Prerequisites

前置条件

  • androidx.compose.ui:ui-test-junit4
    on
    androidTestImplementation
    ,
    androidx.compose.ui:ui-test-manifest
    on
    debugImplementation
    . See
    ../../setup/configuring-test-dependencies/SKILL.md
    .
  • Default activity is
    androidx.activity.ComponentActivity
    (provided by
    ui-test-manifest
    ). For a custom Activity the
    androidTest
    source set MUST declare it in
    AndroidManifest.xml
    .
  • Kotlin source set:
    src/androidTest/kotlin/...
    (instrumentation) or
    src/test/kotlin/...
    (Robolectric host).
  • androidx.compose.ui:ui-test-junit4
    位于
    androidTestImplementation
    ,
    androidx.compose.ui:ui-test-manifest
    位于
    debugImplementation
    。请参阅
    ../../setup/configuring-test-dependencies/SKILL.md
    。
  • 默认 Activity 为
    androidx.activity.ComponentActivity
    (由
    ui-test-manifest
    提供)。对于自定义 Activity,
    androidTest
    source set 必须将其声明在
    AndroidManifest.xml
    中。
  • Kotlin source set:
    src/androidTest/kotlin/...
    (instrumentation)或
    src/test/kotlin/...
    (Robolectric host)。

Workflow

工作流

  • 1. Mirror the production package. Place
    MyButtonTest.kt
    in the same package as
    MyButton.kt
    . The class name is
    <ProductionFile>Test
    (
    SwitchTest.kt
    ,
    LazyListTest.kt
    ).
  • 2. Annotate the class.
    @MediumTest
    is the default budget. Use
    @LargeTest
    only for tests that intentionally take seconds (long-clicks via
    performTouchInput { longClick() }
    , multi-second animations).
    @RunWith(AndroidJUnit4::class)
    is non-negotiable for instrumentation.
  • 3. Declare exactly one rule. Prefer the v2 entry point — it defaults the composition dispatcher to
    StandardTestDispatcher
    , matching
    kotlinx.coroutines.test.runTest
    .
kotlin
import androidx.compose.ui.test.junit4.v2.createComposeRule
import kotlinx.coroutines.test.StandardTestDispatcher

@MediumTest
@RunWith(AndroidJUnit4::class)
class MyButtonTest {
    @get:Rule val rule = createComposeRule(StandardTestDispatcher())
}
For a custom Activity (e.g.
FragmentActivity
, a screen-under-test Activity), use the reified v2 helper:
kotlin
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
@get:Rule val rule = createAndroidComposeRule<FragmentActivity>(StandardTestDispatcher())
Cited from
compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/textfield/TextFieldFocusCustomDialogTest.kt:60
.
  • 4. Hoist state ABOVE
    setContent
    .
    Anything the test wants to mutate or read must be a property declared in the test method, then captured by reference inside the composable.
  • 5. Call
    setContent { }
    INSIDE the
    @Test
    method, not in
    @Before
    .
    Each test owns its own composition. Tests with shared
    setContent
    in
    @Before
    cannot vary content between cases and lose the per-test state setup the framework expects.
  • 6. Follow Test → Find → Assert → Act → Re-assert. The canonical shape from
    compose/material3/material3/src/androidDeviceTest/kotlin/androidx/compose/material3/SwitchTest.kt:240-262
    (the
    switch_stateChange_movesThumb
    test):
kotlin
@Test
fun switch_stateChange_movesThumb() {
    var checked by mutableStateOf(false)                          // STATE (hoisted)
    rule.setMaterialContent(lightColorScheme()) {                  // SET CONTENT (in test body)
        val spacer = @Composable { Spacer(Modifier.size(16.dp).testTag("spacer")) }
        Switch(
            modifier = Modifier.testTag(defaultSwitchTag),
            checked = checked,
            thumbContent = spacer,
            onCheckedChange = { checked = it },
        )
    }

    rule.onNodeWithTag("spacer", useUnmergedTree = true)           // FIND + ASSERT
        .assertLeftPositionInRootIsEqualTo(8.dp)

    rule.runOnIdle { checked = true }                              // ACT (mutate from outside)

    rule.onNodeWithTag("spacer", useUnmergedTree = true)           // RE-ASSERT
        .assertLeftPositionInRootIsEqualTo(28.dp)

    rule.runOnIdle { checked = false }
    rule.onNodeWithTag("spacer", useUnmergedTree = true).assertLeftPositionInRootIsEqualTo(8.dp)
}
  • 7. Read state from outside via
    rule.runOnIdle { … }
    .
    The block runs after
    waitForIdle()
    , so observed values reflect the latest composition.
kotlin
val (index, offset) = rule.runOnIdle {
    state.firstVisibleItemIndex to state.firstVisibleItemScrollOffset
}
Cited from
compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyListTest.kt:903-904
.
  • 8. Write state from outside via
    rule.runOnIdle { … }
    .
    Direct assignment from the test thread races the recomposer.
kotlin
rule.runOnIdle { count = 5 }
  • 1. 与生产代码包保持一致。 将
    MyButtonTest.kt
    放在与
    MyButton.kt
    相同的包中。类名应为
    <ProductionFile>Test
    (
    SwitchTest.kt
    、
    LazyListTest.kt
    )。
  • 2. 为类添加注解。
    @MediumTest
    是默认的耗时等级。仅当测试有意耗时数秒时才使用
    @LargeTest
    ,例如长按(
    performTouchInput { longClick() }
    )或持续数秒的动画。对于 instrumentation,
    @RunWith(AndroidJUnit4::class)
    是必需的。
  • 3. 恰好声明一个 rule。 优先使用 v2 入口——它默认将 composition dispatcher 设置为
    StandardTestDispatcher
    ,与
    kotlinx.coroutines.test.runTest
    保持一致。
kotlin
import androidx.compose.ui.test.junit4.v2.createComposeRule
import kotlinx.coroutines.test.StandardTestDispatcher

@MediumTest
@RunWith(AndroidJUnit4::class)
class MyButtonTest {
    @get:Rule val rule = createComposeRule(StandardTestDispatcher())
}
对于自定义 Activity(例如
FragmentActivity
或被测屏幕对应的 Activity),请使用带 reified 类型的 v2 helper:
kotlin
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
@get:Rule val rule = createAndroidComposeRule<FragmentActivity>(StandardTestDispatcher())
引用自
compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/textfield/TextFieldFocusCustomDialogTest.kt:60
。
  • 4. 将状态提升到
    setContent
    之上。
    测试希望修改或读取的所有内容都必须是测试方法中声明的 property,然后在 composable 内部按引用捕获。
  • 5. 在
    @Test
    方法内部调用
    setContent { }
    ,而不要在
    @Before
    中调用。
    每个测试都应拥有自己的 composition。在
    @Before
    中共享
    setContent
    会导致测试无法在不同用例之间改变内容,也会失去框架所要求的每测试状态准备过程。
  • 6. 遵循 Test → Find → Assert → Act → Re-assert。 标准结构来自
    compose/material3/material3/src/androidDeviceTest/kotlin/androidx/compose/material3/SwitchTest.kt:240-262
    (即
    switch_stateChange_movesThumb
    测试):
kotlin
@Test
fun switch_stateChange_movesThumb() {
    var checked by mutableStateOf(false)                          // STATE (hoisted)
    rule.setMaterialContent(lightColorScheme()) {                  // SET CONTENT (in test body)
        val spacer = @Composable { Spacer(Modifier.size(16.dp).testTag("spacer")) }
        Switch(
            modifier = Modifier.testTag(defaultSwitchTag),
            checked = checked,
            thumbContent = spacer,
            onCheckedChange = { checked = it },
        )
    }

    rule.onNodeWithTag("spacer", useUnmergedTree = true)           // FIND + ASSERT
        .assertLeftPositionInRootIsEqualTo(8.dp)

    rule.runOnIdle { checked = true }                              // ACT (mutate from outside)

    rule.onNodeWithTag("spacer", useUnmergedTree = true)           // RE-ASSERT
        .assertLeftPositionInRootIsEqualTo(28.dp)

    rule.runOnIdle { checked = false }
    rule.onNodeWithTag("spacer", useUnmergedTree = true).assertLeftPositionInRootIsEqualTo(8.dp)
}
  • 7. 通过
    rule.runOnIdle { … }
    从外部读取状态。
    该代码块在
    waitForIdle()
    之后运行,因此观察到的值会反映最新的 composition。
kotlin
val (index, offset) = rule.runOnIdle {
    state.firstVisibleItemIndex to state.firstVisibleItemScrollOffset
}
引用自
compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyListTest.kt:903-904
。
  • 8. 通过
    rule.runOnIdle { … }
    从外部写入状态。
    直接从测试线程赋值会与 recomposer 发生竞态。
kotlin
rule.runOnIdle { count = 5 }

Patterns

模式

Pattern: state hoisted inside vs. above
setContent

模式:在
setContent
内部与上方提升状态

kotlin
// WRONG
@Test
fun toggle() {
    rule.setContent {
        var checked by remember { mutableStateOf(false) }   // <-- trapped inside composition
        Switch(checked = checked, onCheckedChange = { checked = it })
    }
    rule.runOnIdle { checked = true }                       // does not compile / has no reference
}
// WRONG because: the test thread has no reference to `checked`. The state cannot be driven
// from outside, and the test can only verify the very first frame.
kotlin
// RIGHT
@Test
fun toggle() {
    var checked by mutableStateOf(false)                    // <-- hoisted to test scope
    rule.setContent {
        Switch(checked = checked, onCheckedChange = { checked = it })
    }
    rule.onNodeWithTag("switch").assertIsOff()
    rule.runOnIdle { checked = true }                       // mutate via runOnIdle
    rule.onNodeWithTag("switch").assertIsOn()
}
kotlin
// WRONG
@Test
fun toggle() {
    rule.setContent {
        var checked by remember { mutableStateOf(false) }   // <-- trapped inside composition
        Switch(checked = checked, onCheckedChange = { checked = it })
    }
    rule.runOnIdle { checked = true }                       // does not compile / has no reference
}
// WRONG because: the test thread has no reference to `checked`. The state cannot be driven
// from outside, and the test can only verify the very first frame.
kotlin
// RIGHT
@Test
fun toggle() {
    var checked by mutableStateOf(false)                    // <-- hoisted to test scope
    rule.setContent {
        Switch(checked = checked, onCheckedChange = { checked = it })
    }
    rule.onNodeWithTag("switch").assertIsOff()
    rule.runOnIdle { checked = true }                       // mutate via runOnIdle
    rule.onNodeWithTag("switch").assertIsOn()
}

Pattern:
setContent
in
@Before

模式:在
@Before
中设置
setContent

kotlin
// WRONG
@Before
fun setUp() {
    rule.setContent { MyScreen(state) }                     // <-- shared across all tests
}

@Test fun stateA() { /* mutate `state` here, but it was already composed without this case */ }
kotlin
// RIGHT
@Test
fun stateA() {
    val state = ScreenState(initial = "A")
    rule.setContent { MyScreen(state) }                     // <-- per-test composition
    rule.onNodeWithTag("title").assertTextEquals("A")
}
kotlin
// WRONG
@Before
fun setUp() {
    rule.setContent { MyScreen(state) }                     // <-- shared across all tests
}

@Test fun stateA() { /* mutate `state` here, but it was already composed without this case */ }
kotlin
// RIGHT
@Test
fun stateA() {
    val state = ScreenState(initial = "A")
    rule.setContent { MyScreen(state) }                     // <-- per-test composition
    rule.onNodeWithTag("title").assertTextEquals("A")
}

Pattern: one rule per class — never mix with
runComposeUiTest

模式:每个类一个 rule——绝不与
runComposeUiTest
混用

kotlin
// WRONG
class MyTest {
    @get:Rule val rule = createComposeRule(StandardTestDispatcher())

    @Test fun a() = runComposeUiTest {                      // <-- second test environment
        setContent { /* … */ }
    }
}
// WRONG because: createComposeRule and runComposeUiTest each manage an independent test
// environment (composition + MainTestClock + IdlingResourceRegistry). Mixing them produces
// undefined behavior. KDoc warns explicitly: see the ComposeUiTest.android.kt KDoc on
// runComposeUiTest, runAndroidComposeUiTest, runEmptyComposeUiTest, and the v2 variants.
kotlin
// RIGHT — pick exactly one entry point per class
class MyRuleTest {
    @get:Rule val rule = createComposeRule(StandardTestDispatcher())
    @Test fun a() { rule.setContent { /* … */ } }
}

// or
class MyFunctionTest {
    @Test fun a() = runComposeUiTest { setContent { /* … */ } }
}
kotlin
// WRONG
class MyTest {
    @get:Rule val rule = createComposeRule(StandardTestDispatcher())

    @Test fun a() = runComposeUiTest {                      // <-- second test environment
        setContent { /* … */ }
    }
}
// WRONG because: createComposeRule and runComposeUiTest each manage an independent test
// environment (composition + MainTestClock + IdlingResourceRegistry). Mixing them produces
// undefined behavior. KDoc warns explicitly: see the ComposeUiTest.android.kt KDoc on
// runComposeUiTest, runAndroidComposeUiTest, runEmptyComposeUiTest, and the v2 variants.
kotlin
// RIGHT — pick exactly one entry point per class
class MyRuleTest {
    @get:Rule val rule = createComposeRule(StandardTestDispatcher())
    @Test fun a() { rule.setContent { /* … */ } }
}

// or
class MyFunctionTest {
    @Test fun a() = runComposeUiTest { setContent { /* … */ } }
}

Pattern: custom Activity needs its own manifest entry

模式:自定义 Activity 需要独立的 manifest 条目

kotlin
// RIGHT — ComponentActivity comes free from ui-test-manifest
@get:Rule val rule = createComposeRule(StandardTestDispatcher())
kotlin
// RIGHT — a custom Activity must be declared in src/androidTest/AndroidManifest.xml
@get:Rule val rule = createAndroidComposeRule<MyActivity>(StandardTestDispatcher())
xml
<!-- src/androidTest/AndroidManifest.xml -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application>
        <activity android:name=".MyActivity" />
    </application>
</manifest>
kotlin
// RIGHT — ComponentActivity comes free from ui-test-manifest
@get:Rule val rule = createComposeRule(StandardTestDispatcher())
kotlin
// RIGHT — a custom Activity must be declared in src/androidTest/AndroidManifest.xml
@get:Rule val rule = createAndroidComposeRule<MyActivity>(StandardTestDispatcher())
xml
<!-- src/androidTest/AndroidManifest.xml -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application>
        <activity android:name=".MyActivity" />
    </application>
</manifest>

Pattern:
MediumTest
vs
LargeTest

模式:
MediumTest
与
LargeTest

kotlin
@MediumTest                     // default — sub-second tests
class SwitchTest { /* … */ }

@LargeTest                      // long-clicks, multi-second animations
class CombinedClickableTest { /* … */ }
@MediumTest
is used by
SwitchTest.kt:76
and most material3/foundation suites.
@LargeTest
is reserved for tests whose total wall time intentionally exceeds the medium budget.
kotlin
@MediumTest                     // default — sub-second tests
class SwitchTest { /* … */ }

@LargeTest                      // long-clicks, multi-second animations
class CombinedClickableTest { /* … */ }
@MediumTest
正在
SwitchTest.kt:76
中使用,也用于大多数 material3/foundation 测试套件。
@LargeTest
仅用于总耗时有意超过中等耗时预算的测试。

Mandatory rules

强制规则

  • MUST annotate the class with
    @RunWith(AndroidJUnit4::class)
    and a size annotation (
    @MediumTest
    by default).
  • MUST declare exactly one rule per class — either
    createComposeRule(...)
    ,
    createAndroidComposeRule<A>(...)
    , or
    createEmptyComposeRule()
    . MUST NOT combine a
    @get:Rule
    rule with
    runComposeUiTest { }
    in the same class. KDoc cited at
    compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeUiTest.android.kt:158, 204, 247, 338
    .
  • MUST prefer the v2 entry points
    androidx.compose.ui.test.junit4.v2.createComposeRule
    /
    createAndroidComposeRule
    . The v1 forms are
    @Deprecated(level = WARNING)
    because they use
    UnconfinedTestDispatcher
    instead of
    StandardTestDispatcher
    (skydoves directive #6).
  • MUST hoist mutable state as
    var x by mutableStateOf(...)
    above
    setContent { }
    whenever the test must drive or observe it.
  • MUST call
    rule.setContent { }
    inside the
    @Test
    method. MUST NOT call it in
    @Before
    .
  • MUST mutate state from outside via
    rule.runOnIdle { state = … }
    (or
    rule.runOnUiThread { … }
    for cases where idling first is undesirable, e.g.
    mainClock.autoAdvance = false
    ). See skydoves directive #5. Detail in
    ../../synchronization/synchronizing-with-idle/SKILL.md
    .
  • MUST read state from outside via
    rule.runOnIdle { state.value }
    . Direct reads from the test thread snapshot the wrong frame.
  • PREFERRED: find by
    Modifier.testTag(...)
    declared as a
    const
    in production (skydoves directive #1). Text finders are i18n-fragile. See
    ../../finders/finding-nodes-by-tag-text-content/SKILL.md
    .
  • PREFERRED: Test → Find → Assert → Act → Re-assert per logical state change. Multi-step tests stack additional Act → Re-assert pairs (
    SwitchTest.kt:140-147
    ).
  • 必须使用
    @RunWith(AndroidJUnit4::class)
    和一个耗时注解为类添加注解(默认使用
    @MediumTest
    )。
  • 必须在每个类中恰好声明一个 rule,即
    createComposeRule(...)
    、
    createAndroidComposeRule<A>(...)
    或
    createEmptyComposeRule()
    之一。绝不能在同一类中组合使用
    @get:Rule
    rule 和
    runComposeUiTest { }
    。KDoc 引用位置:
    compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeUiTest.android.kt:158, 204, 247, 338
    。
  • 必须优先使用 v2 入口
    androidx.compose.ui.test.junit4.v2.createComposeRule
    /
    createAndroidComposeRule
    。v1 形式已被标记为
    @Deprecated(level = WARNING)
    ,因为它们使用
    UnconfinedTestDispatcher
    而不是
    StandardTestDispatcher
    (skydoves directive #6)。
  • 必须在测试需要驱动或观察状态时,将可变状态声明为
    var x by mutableStateOf(...)
    并放置在
    setContent { }
    之上。
  • 必须在
    @Test
    方法内部调用
    rule.setContent { }
    。绝不能在
    @Before
    中调用。
  • 必须通过
    rule.runOnIdle { state = … }
    从外部修改状态;对于不希望先等待空闲的场景,可以使用
    rule.runOnUiThread { … }
    ,例如
    mainClock.autoAdvance = false
    。请参阅 skydoves directive #5。详细信息见
    ../../synchronization/synchronizing-with-idle/SKILL.md
    。
  • 必须通过
    rule.runOnIdle { state.value }
    从外部读取状态。直接从测试线程读取会得到错误的帧快照。
  • **首选:**使用
    Modifier.testTag(...)
    查找节点,并将 tag 作为生产代码中的
    const
    声明(skydoves directive #1)。基于文本的查找器容易受到国际化影响。请参阅
    ../../finders/finding-nodes-by-tag-text-content/SKILL.md
    。
  • **首选:**每次逻辑状态变更都遵循 Test → Find → Assert → Act → Re-assert。多步骤测试可以叠加额外的 Act → Re-assert 对(
    SwitchTest.kt:140-147
    )。

Verification

验证

  • Class has
    @RunWith(AndroidJUnit4::class)
    +
    @MediumTest
    (or
    @LargeTest
    ).
  • Exactly one
    @get:Rule
    declared and it is a
    createComposeRule(...)
    /
    createAndroidComposeRule(...)
    /
    createEmptyComposeRule()
    instance.
  • No
    runComposeUiTest { }
    invocation appears in the same class.
  • setContent { }
    appears inside
    @Test
    methods only — not in
    @Before
    /
    @BeforeEach
    .
  • Every state the test mutates is declared with
    var x by mutableStateOf(...)
    above
    setContent
    , captured by reference inside the composable.
  • All state mutations after
    setContent
    go through
    rule.runOnIdle { }
    or
    rule.runOnUiThread { }
    .
  • All cross-frame state reads happen inside
    rule.runOnIdle { }
    .
  • No
    Thread.sleep
    appears in the test method (skydoves directive #7). See
    ../../synchronization/synchronizing-with-idle/SKILL.md
    .
  • Custom Activities are declared in
    src/androidTest/AndroidManifest.xml
    (not just the production
    AndroidManifest.xml
    ).
  • 类包含
    @RunWith(AndroidJUnit4::class)
    +
    @MediumTest
    (或
    @LargeTest
    )。
  • 恰好声明一个
    @get:Rule
    ,且它是
    createComposeRule(...)
    /
    createAndroidComposeRule(...)
    /
    createEmptyComposeRule()
    实例。
  • 同一类中未出现
    runComposeUiTest { }
    调用。
  • setContent { }
    仅出现在
    @Test
    方法中——不得出现在
    @Before
    /
    @BeforeEach
    中。
  • 测试修改的每项状态都通过
    var x by mutableStateOf(...)
    声明在
    setContent
    之上,并在 composable 内部按引用捕获。
  • setContent
    之后的所有状态修改都通过
    rule.runOnIdle { }
    或
    rule.runOnUiThread { }
    完成。
  • 所有跨帧状态读取都在
    rule.runOnIdle { }
    内完成。
  • 测试方法中未出现
    Thread.sleep
    (skydoves directive #7)。请参阅
    ../../synchronization/synchronizing-with-idle/SKILL.md
    。
  • 自定义 Activity 已声明在
    src/androidTest/AndroidManifest.xml
    中,而不只是
    production AndroidManifest.xml
    。

References

参考资料

  • Compose testing overview: https://developer.android.com/develop/ui/compose/testing
  • Compose testing setup: https://developer.android.com/develop/ui/compose/testing#setup
  • Compose testing cheat sheet: https://developer.android.com/develop/ui/compose/testing-cheatsheet
  • Canonical class skeleton:
    compose/material3/material3/src/androidDeviceTest/kotlin/androidx/compose/material3/SwitchTest.kt:76-263
  • Custom Activity rule:
    compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/textfield/TextFieldFocusCustomDialogTest.kt:57-60
  • v2 rule factory:
    compose/ui/ui-test-junit4/src/androidMain/kotlin/androidx/compose/ui/test/junit4/v2/AndroidComposeTestRule.android.kt
  • "Do not mix rule and runComposeUiTest" KDoc:
    compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeUiTest.android.kt:158, 204, 247, 338
  • runOnIdle
    semantics:
    compose/ui/ui-test-junit4/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/junit4/ComposeTestRule.jvmAndAndroid.kt
  • Compose 测试概览:https://developer.android.com/develop/ui/compose/testing
  • Compose 测试设置:https://developer.android.com/develop/ui/compose/testing#setup
  • Compose 测试速查表:https://developer.android.com/develop/ui/compose/testing-cheatsheet
  • 标准类骨架:
    compose/material3/material3/src/androidDeviceTest/kotlin/androidx/compose/material3/SwitchTest.kt:76-263
  • 自定义 Activity rule:
    compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/textfield/TextFieldFocusCustomDialogTest.kt:57-60
  • v2 rule factory:
    compose/ui/ui-test-junit4/src/androidMain/kotlin/androidx/compose/ui/test/junit4/v2/AndroidComposeTestRule.android.kt
  • “禁止混用 rule 与
    runComposeUiTest
    ”的 KDoc:
    compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeUiTest.android.kt:158, 204, 247, 338
  • runOnIdle
    语义:
    compose/ui/ui-test-junit4/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/junit4/ComposeTestRule.jvmAndAndroid.kt