entering-text

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Entering Text — performTextInput, performTextReplacement, performImeAction

输入文本——performTextInput、performTextReplacement、performImeAction

Compose text fields expose semantics actions for IME-style edits. The test API wraps those actions so a single call types text, replaces text, clears text, sets a selection, or fires the IME action. Every entry point auto-focuses the node when needed and asserts that the node is enabled and editable, surfacing precise errors when one of those preconditions fails.
Compose 文本输入框暴露了用于 IME 风格编辑的 semantics actions。测试 API 对这些操作进行了封装,因此只需一次调用即可输入文本、替换文本、清除文本、设置选区或触发 IME action。每个入口都会在必要时自动聚焦节点,并断言节点已启用且可编辑;当前置条件不满足时,会给出精确的错误信息。

When to use this skill

何时使用此 skill

  • The test types into
    TextField
    ,
    OutlinedTextField
    ,
    BasicTextField
    , or any composable that exposes the
    InsertTextAtCursor
    /
    SetText
    semantics actions.
  • The test fires an IME action —
    ImeAction.Next
    to advance focus,
    ImeAction.Done
    to dismiss the keyboard,
    ImeAction.Search
    /
    Send
    /
    Go
    to trigger a form submit.
  • The test must clear an existing value, or replace the full value with new text.
  • The test asserts cursor or selection state with
    performTextInputSelection(TextRange(...))
    .
  • 测试需要向
    TextField
    、
    OutlinedTextField
    、
    BasicTextField
    或任何暴露
    InsertTextAtCursor
    /
    SetText
    semantics actions 的 composable 中输入文本。
  • 测试需要触发 IME action,例如使用
    ImeAction.Next
    移动焦点、使用
    ImeAction.Done
    收起键盘,或使用
    ImeAction.Search
    /
    Send
    /
    Go
    触发表单提交。
  • 测试需要清除已有值,或使用新文本替换完整值。
  • 测试需要通过
    performTextInputSelection(TextRange(...))
    断言光标或选区状态。

When NOT to use this skill

何时不应使用此 skill

  • The test sends an arbitrary key shortcut into a focused field (e.g.
    Ctrl+A
    ,
    Tab
    , arrow keys). Use
    ../injecting-mouse-and-keyboard/SKILL.md
    .
  • The test only checks the displayed text without typing — assert via
    ../../assertions/asserting-node-state-and-text/SKILL.md
    .
  • A finder cannot locate the text field. Verify the matcher first via
    ../../finders/finding-nodes-by-tag-text-content/SKILL.md
    .
  • The test asserts state restoration of the typed text after rotation. See
    ../../setup/configuring-test-dependencies/SKILL.md
    and
    StateRestorationTester
    .
  • 测试需要向已聚焦的输入框发送任意快捷键(例如
    Ctrl+A
    、
    Tab
    、方向键)。请使用
    ../injecting-mouse-and-keyboard/SKILL.md
    。
  • 测试只检查显示的文本而不执行输入——请通过
    ../../assertions/asserting-node-state-and-text/SKILL.md
    进行断言。
  • finder 无法定位到文本输入框。请先通过
    ../../finders/finding-nodes-by-tag-text-content/SKILL.md
    验证 matcher。
  • 测试需要断言旋转屏幕后输入文本的状态恢复。请参阅
    ../../setup/configuring-test-dependencies/SKILL.md
    和
    StateRestorationTester
    。

Prerequisites

前置条件

  • androidx.compose.ui:ui-test-junit4
    (or
    ui-test
    for
    runComposeUiTest
    ) configured per
    ../../setup/configuring-test-dependencies/SKILL.md
    .
  • The
    TextField
    carries
    Modifier.testTag("…")
    from production code so the test selects it deterministically.
  • The field is
    enabled = true
    .
    performTextInput
    calls
    assert(isEnabled())
    before doing anything (TextActions.kt:125).
  • For
    performImeAction
    : the field declares both
    ImeAction != ImeAction.Default
    (via
    KeyboardOptions(imeAction = …)
    ) and an
    OnImeAction
    handler (via
    KeyboardActions(...)
    or default keyboard actions). The action assertion checks both (TextActions.kt:99-100).
  • 已按
    ../../setup/configuring-test-dependencies/SKILL.md
    配置
    androidx.compose.ui:ui-test-junit4
    (或用于
    runComposeUiTest
    的
    ui-test
    )。
  • TextField
    在生产代码中带有
    Modifier.testTag("…")
    ,以便测试确定性地选择该节点。
  • 输入框的
    enabled = true
    。
    performTextInput
    在执行任何操作前会调用
    assert(isEnabled())
    (TextActions.kt:125)。
  • 对于
    performImeAction
    :输入框必须同时声明非默认的
    ImeAction != ImeAction.Default
    (通过
    KeyboardOptions(imeAction = …)
    )和
    OnImeAction
    处理器(通过
    KeyboardActions(...)
    或默认键盘操作)。action 断言会同时检查这两项(TextActions.kt:99-100)。

Workflow

工作流

  1. Type text at the cursor —
    performTextInput(text)
    (TextActions.kt:37-41). Internally invokes
    SemanticsActions.InsertTextAtCursor
    with
    AnnotatedString(text)
    . Auto-focuses the node first when it is not focused (
    getNodeAndFocus
    — TextActions.kt:119-138). Throws
    AssertionError("Failed to perform text input.")
    if the node is not enabled, not focusable, or does not advertise
    InsertTextAtCursor
    .
kotlin
rule.onNodeWithTag(Tag).performTextInput("Hello ")
  1. Replace the entire text —
    performTextReplacement(text)
    (TextActions.kt:81-84). Invokes
    SemanticsActions.SetText
    , which clears existing text and inserts new text. Use this when the field already has a value the test wants to overwrite. MUST NOT be used to "type more characters" — see the WRONG/RIGHT pair below.
kotlin
rule.onNodeWithTag(Tag).performTextReplacement("New value")
  1. Clear the text —
    performTextClearance()
    (TextActions.kt:28-30). Sugar for
    performTextReplacement("")
    . The field must be focusable + have
    SetText
    .
kotlin
rule.onNodeWithTag(Tag).performTextClearance()
  1. Set the selection / cursor —
    performTextInputSelection(selection: TextRange, relativeToOriginalText: Boolean = true)
    (TextActions.kt:61-72). Maps to
    SemanticsActions.SetSelection
    . When
    relativeToOriginalText = true
    , indices refer to the original (untransformed) text;
    false
    makes them refer to the post-
    VisualTransformation
    text.
kotlin
rule.onNodeWithTag(Tag).performTextInput("Hello World")
rule.onNodeWithTag(Tag).performTextInputSelection(TextRange(0, 5)) // selects "Hello"
  1. Fire the IME action —
    performImeAction()
    (TextActions.kt:97-117). Pre-conditions, in order:
    • assert(hasPerformImeAction())
      — the field declares
      OnImeAction
      .
    • assert(!hasImeAction(ImeAction.Default))
      — the action is something other than the default.
    • tryPerformAccessibilityChecks()
      .
    • Auto-focus via
      getNodeAndFocus(requireEditable = false)
      .
    • Invoke
      OnImeAction
      and require it returned
      true
      ; otherwise throw
      AssertionError("Failed to perform IME action, handler returned false.")
      .
kotlin
rule.onNodeWithTag(InitialFieldTag).performImeAction()
  1. Pair with
    assertTextEquals
    to confirm the expected post-state. The merged-tree default applies to text assertions exactly as to finders — see
    ../../assertions/asserting-node-state-and-text/SKILL.md
    .
  1. 在光标处输入文本——
    performTextInput(text)
    (TextActions.kt:37-41)。内部使用
    AnnotatedString(text)
    调用
    SemanticsActions.InsertTextAtCursor
    。当节点尚未获得焦点时,会先自动聚焦(
    getNodeAndFocus
    ——TextActions.kt:119-138)。如果节点未启用、不可聚焦,或未提供
    InsertTextAtCursor
    ,则抛出
    AssertionError("Failed to perform text input.")
    。
kotlin
rule.onNodeWithTag(Tag).performTextInput("Hello ")
  1. 替换全部文本——
    performTextReplacement(text)
    (TextActions.kt:81-84)。调用
    SemanticsActions.SetText
    ,清除已有文本并插入新文本。当输入框已包含测试希望覆盖的值时,应使用此方法。不得将其用于“继续输入更多字符”——请参阅下方错误/正确示例。
kotlin
rule.onNodeWithTag(Tag).performTextReplacement("New value")
  1. 清除文本——
    performTextClearance()
    (TextActions.kt:28-30)。这是
    performTextReplacement("")
    的语法糖。输入框必须可聚焦并提供
    SetText
    。
kotlin
rule.onNodeWithTag(Tag).performTextClearance()
  1. 设置选区或光标——
    performTextInputSelection(selection: TextRange, relativeToOriginalText: Boolean = true)
    (TextActions.kt:61-72)。映射到
    SemanticsActions.SetSelection
    。当
    relativeToOriginalText = true
    时,索引指向原始、未经转换的文本;当其为
    false
    时,索引指向应用
    VisualTransformation
    后的文本。
kotlin
rule.onNodeWithTag(Tag).performTextInput("Hello World")
rule.onNodeWithTag(Tag).performTextInputSelection(TextRange(0, 5)) // selects "Hello"
  1. 触发 IME action——
    performImeAction()
    (TextActions.kt:97-117)。按顺序检查以下前置条件:
    • assert(hasPerformImeAction())
      ——输入框声明了
      OnImeAction
      。
    • assert(!hasImeAction(ImeAction.Default))
      ——action 不是默认值。
    • tryPerformAccessibilityChecks()
      。
    • 通过
      getNodeAndFocus(requireEditable = false)
      自动聚焦。
    • 调用
      OnImeAction
      ,并要求其返回
      true
      ;否则抛出
      AssertionError("Failed to perform IME action, handler returned false.")
      。
kotlin
rule.onNodeWithTag(InitialFieldTag).performImeAction()
  1. 与
    assertTextEquals
    配合使用
    ,以确认预期的操作后状态。merged-tree 默认行为对文本断言的生效方式与对 finders 的生效方式完全相同——请参阅
    ../../assertions/asserting-node-state-and-text/SKILL.md
    。

Patterns

模式

Pattern: Append (
performTextInput
) vs replace (
performTextReplacement
)

模式:追加(
performTextInput
)与替换(
performTextReplacement
)

The most common gotcha — the two APIs look interchangeable but compose differently.
kotlin
// WRONG
rule.onNodeWithTag(Tag).performTextInput("hello")
rule.onNodeWithTag(Tag).performTextInput("world")
rule.onNodeWithTag(Tag).assertTextEquals("world")
// WRONG because: performTextInput maps to InsertTextAtCursor, not SetText. The cursor
// remains at the end of "hello" after the first call, so the second call inserts
// "world" there. Final value is "helloworld" — assertion fails.
kotlin
// RIGHT
rule.onNodeWithTag(Tag).performTextInput("hello")
rule.onNodeWithTag(Tag).performTextReplacement("world")
rule.onNodeWithTag(Tag).assertTextEquals("world")
performTextReplacement
calls
SemanticsActions.SetText
(TextActions.kt:83), which clears existing characters before inserting the new text — equivalent to the IME's "set composing region to whole text and replace" path. Use it any time the second call should overwrite, not append.
这是最常见的陷阱——两个 API 看起来可以互换,但实现方式不同。
kotlin
// WRONG
rule.onNodeWithTag(Tag).performTextInput("hello")
rule.onNodeWithTag(Tag).performTextInput("world")
rule.onNodeWithTag(Tag).assertTextEquals("world")
// WRONG because: performTextInput maps to InsertTextAtCursor, not SetText. The cursor
// remains at the end of "hello" after the first call, so the second call inserts
// "world" there. Final value is "helloworld" — assertion fails.
kotlin
// RIGHT
rule.onNodeWithTag(Tag).performTextInput("hello")
rule.onNodeWithTag(Tag).performTextReplacement("world")
rule.onNodeWithTag(Tag).assertTextEquals("world")
performTextReplacement
调用
SemanticsActions.SetText
(TextActions.kt:83),会在插入新文本前清除已有字符,等价于 IME 的“将 composing region 设置为整段文本并替换”路径。当第二次调用应覆盖而不是追加文本时,应始终使用此方法。

Pattern: Canonical insert + assert

模式:标准插入与断言

From
BasicTextFieldTest.kt:171-194
:
kotlin
@Test
fun textFieldState_textChange_updatesState() {
    val state = TextFieldState("Hello ", TextRange(Int.MAX_VALUE))
    inputMethodInterceptor.setTextFieldTestContent {
        BasicTextField(state = state, modifier = Modifier.fillMaxSize().testTag(Tag))
    }

    rule.onNodeWithTag(Tag).performTextInput("World!")

    rule.runOnIdle { assertThat(state.text.toString()).isEqualTo("Hello World!") }
}

@Test
fun textFieldState_textChange_updatesSemantics() {
    val state = TextFieldState("Hello ", TextRange(Int.MAX_VALUE))
    inputMethodInterceptor.setTextFieldTestContent {
        BasicTextField(state = state, modifier = Modifier.fillMaxSize().testTag(Tag))
    }

    rule.onNodeWithTag(Tag).performTextInput("World!")

    rule.onNodeWithTag(Tag).assertTextEquals("Hello World!")
}
The cursor is positioned at
TextRange(Int.MAX_VALUE)
(end of text) when constructing
TextFieldState
.
performTextInput("World!")
inserts at that cursor — final value
"Hello World!"
. State reads happen inside
runOnIdle
(skydoves hot take #5).
摘自
BasicTextFieldTest.kt:171-194
:
kotlin
@Test
fun textFieldState_textChange_updatesState() {
    val state = TextFieldState("Hello ", TextRange(Int.MAX_VALUE))
    inputMethodInterceptor.setTextFieldTestContent {
        BasicTextField(state = state, modifier = Modifier.fillMaxSize().testTag(Tag))
    }

    rule.onNodeWithTag(Tag).performTextInput("World!")

    rule.runOnIdle { assertThat(state.text.toString()).isEqualTo("Hello World!") }
}

@Test
fun textFieldState_textChange_updatesSemantics() {
    val state = TextFieldState("Hello ", TextRange(Int.MAX_VALUE))
    inputMethodInterceptor.setTextFieldTestContent {
        BasicTextField(state = state, modifier = Modifier.fillMaxSize().testTag(Tag))
    }

    rule.onNodeWithTag(Tag).performTextInput("World!")

    rule.onNodeWithTag(Tag).assertTextEquals("Hello World!")
}
构造
TextFieldState
时,光标位于
TextRange(Int.MAX_VALUE)
(文本末尾)。
performTextInput("World!")
会在该光标位置插入——最终值为
"Hello World!"
。状态读取必须在
runOnIdle
中进行(skydoves hot take #5)。

Pattern: Replace then assert —
BasicTextFieldTest.kt:442-466

模式:替换后断言——
BasicTextFieldTest.kt:442-466

kotlin
@Test
fun textField_whenStateObjectChanges_restartsInput() {
    val state1 = TextFieldState("Hello")
    val state2 = TextFieldState("World")
    var toggleState by mutableStateOf(true)
    val state by derivedStateOf { if (toggleState) state1 else state2 }
    inputMethodInterceptor.setTextFieldTestContent {
        BasicTextField(
            state = state,
            enabled = true,
            modifier = Modifier.fillMaxSize().testTag(Tag),
        )
    }

    with(rule.onNodeWithTag(Tag)) {
        performTextReplacement("Compose")
        assertTextEquals("Compose")
    }
    toggleState = !toggleState
    with(rule.onNodeWithTag(Tag)) {
        performTextReplacement("Compose2")
        assertTextEquals("Compose2")
    }
    assertThat(state1.text.toString()).isEqualTo("Compose")
    assertThat(state2.text.toString()).isEqualTo("Compose2")
}
performTextReplacement
overwrites whatever the field's current value happens to be — making it the right call when state is rotated underneath.
kotlin
@Test
fun textField_whenStateObjectChanges_restartsInput() {
    val state1 = TextFieldState("Hello")
    val state2 = TextFieldState("World")
    var toggleState by mutableStateOf(true)
    val state by derivedStateOf { if (toggleState) state1 else state2 }
    inputMethodInterceptor.setTextFieldTestContent {
        BasicTextField(
            state = state,
            enabled = true,
            modifier = Modifier.fillMaxSize().testTag(Tag),
        )
    }

    with(rule.onNodeWithTag(Tag)) {
        performTextReplacement("Compose")
        assertTextEquals("Compose")
    }
    toggleState = !toggleState
    with(rule.onNodeWithTag(Tag)) {
        performTextReplacement("Compose2")
        assertTextEquals("Compose2")
    }
    assertThat(state1.text.toString()).isEqualTo("Compose")
    assertThat(state2.text.toString()).isEqualTo("Compose2")
}
performTextReplacement
会覆盖输入框当前已有的值,因此当底层状态发生切换时,它是正确的选择。

Pattern: Clearing then refilling

模式:清除后重新输入

kotlin
rule.onNodeWithTag(Tag).performTextClearance()
rule.onNodeWithTag(Tag).performTextInput("Different")
rule.onNodeWithTag(Tag).assertTextEquals("Different")
performTextClearance
is sugar for
performTextReplacement("")
(TextActions.kt:28-30). After it runs, the cursor is at position 0, so a follow-up
performTextInput
simply inserts at the start.
kotlin
rule.onNodeWithTag(Tag).performTextClearance()
rule.onNodeWithTag(Tag).performTextInput("Different")
rule.onNodeWithTag(Tag).assertTextEquals("Different")
performTextClearance
是
performTextReplacement("")
的语法糖(TextActions.kt:28-30)。执行后,光标位于位置 0,因此后续的
performTextInput
会直接插入到开头。

Pattern: IME-action focus chain (
Next
advances focus)

模式:IME action 焦点链(
Next
移动焦点)

From
DefaultKeyboardActionsTest.kt:130-149
:
kotlin
// Show keyboard.
rule.onNodeWithTag(initialTextField).performClick()
inputMethodInterceptor.assertSessionActive()
keyboardController.show()

// Act.
rule.onNodeWithTag(initialTextField).performImeAction()

// Assert.
when (imeAction) {
    Next -> {
        // Focus moves to the next item.
        assertThat(focusState1).isFalse()
        assertThat(focusState2).isFalse()
        assertThat(focusState3).isTrue()
    }
    Previous -> {
        // Focus moves to the previous item.
        assertThat(focusState1).isTrue()
        assertThat(focusState2).isFalse()
        assertThat(focusState3).isFalse()
    }
    Done -> {
        // No change to focus state.
        assertThat(focusState1).isFalse()
        assertThat(focusState2).isTrue()
        assertThat(focusState3).isFalse()

        // Software keyboard is hidden.
        keyboardController.assertHidden()
    }
}
Production must declare a non-default
ImeAction
for
performImeAction
to be valid:
kotlin
BasicTextField(
    state = state,
    keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
    modifier = Modifier.testTag(InitialFieldTag),
)
performImeAction
asserts
!hasImeAction(ImeAction.Default)
first (TextActions.kt:100). Forgetting the
keyboardOptions
parameter yields
AssertionError("Failed to perform IME action.")
.
摘自
DefaultKeyboardActionsTest.kt:130-149
:
kotlin
// Show keyboard.
rule.onNodeWithTag(initialTextField).performClick()
inputMethodInterceptor.assertSessionActive()
keyboardController.show()

// Act.
rule.onNodeWithTag(initialTextField).performImeAction()

// Assert.
when (imeAction) {
    Next -> {
        // Focus moves to the next item.
        assertThat(focusState1).isFalse()
        assertThat(focusState2).isFalse()
        assertThat(focusState3).isTrue()
    }
    Previous -> {
        // Focus moves to the previous item.
        assertThat(focusState1).isTrue()
        assertThat(focusState2).isFalse()
        assertThat(focusState3).isFalse()
    }
    Done -> {
        // No change to focus state.
        assertThat(focusState1).isFalse()
        assertThat(focusState2).isTrue()
        assertThat(focusState3).isFalse()

        // Software keyboard is hidden.
        keyboardController.assertHidden()
    }
}
生产代码必须声明非默认的
ImeAction
,
performImeAction
才能有效执行:
kotlin
BasicTextField(
    state = state,
    keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
    modifier = Modifier.testTag(InitialFieldTag),
)
performImeAction
首先断言
!hasImeAction(ImeAction.Default)
(TextActions.kt:100)。遗漏
keyboardOptions
参数会抛出
AssertionError("Failed to perform IME action.")
。

Pattern: Set selection before replacing a substring

模式:替换子字符串前设置选区

kotlin
rule.onNodeWithTag(Tag).performTextInput("Hello World")
rule.onNodeWithTag(Tag).performTextInputSelection(TextRange(6, 11)) // select "World"
rule.onNodeWithTag(Tag).performTextInput("Compose")              // selection replaced
rule.onNodeWithTag(Tag).assertTextEquals("Hello Compose")
SemanticsActions.SetSelection
honours the same path the IME uses, so a follow-up
InsertTextAtCursor
replaces the active selection with the new text. Pass
relativeToOriginalText = false
if the field installs a
VisualTransformation
(e.g. password mask, currency formatter) and the indices were computed against the displayed string.
kotlin
rule.onNodeWithTag(Tag).performTextInput("Hello World")
rule.onNodeWithTag(Tag).performTextInputSelection(TextRange(6, 11)) // select "World"
rule.onNodeWithTag(Tag).performTextInput("Compose")              // selection replaced
rule.onNodeWithTag(Tag).assertTextEquals("Hello Compose")
SemanticsActions.SetSelection
遵循与 IME 相同的路径,因此后续的
InsertTextAtCursor
会用新文本替换当前选区。如果输入框安装了
VisualTransformation
(例如密码掩码、货币格式化器),且索引是基于显示字符串计算的,请传入
relativeToOriginalText = false
。

Pattern: Disabled or non-editable field — clear error

模式:禁用或不可编辑的输入框——清晰的错误信息

If the field is
enabled = false
or the matcher resolves to a
Text
instead of a
TextField
,
performTextInput
throws
AssertionError("Failed to perform text input.")
. The chain is:
  1. tryPerformAccessibilityChecks()
    .
  2. assert(isEnabled())
    .
  3. assert(hasRequestFocusAction())
    .
  4. assert(hasSetTextAction())
    and
    assert(hasInsertTextAtCursorAction())
    (TextActions.kt:127-129).
When the assertion fires, dump the semantics tree via
../../debug/printing-the-semantics-tree/SKILL.md
to confirm the matcher is not selecting a static
Text
.
如果输入框的
enabled = false
,或者 matcher 解析到的是
Text
而非
TextField
,
performTextInput
会抛出
AssertionError("Failed to perform text input.")
。检查链如下:
  1. tryPerformAccessibilityChecks()
    。
  2. assert(isEnabled())
    。
  3. assert(hasRequestFocusAction())
    。
  4. assert(hasSetTextAction())
    和
    assert(hasInsertTextAtCursorAction())
    (TextActions.kt:127-129)。
断言触发后,请通过
../../debug/printing-the-semantics-tree/SKILL.md
输出 semantics tree,以确认 matcher 没有选中静态
Text
。

Mandatory rules

强制规则

  • MUST use
    performTextReplacement
    to overwrite an existing value. MUST NOT chain two
    performTextInput
    calls expecting the second to replace the first — they concatenate at the cursor.
  • MUST declare a non-default
    ImeAction
    (e.g.
    KeyboardOptions(imeAction = ImeAction.Next)
    ) before calling
    performImeAction
    . The API asserts
    !hasImeAction(ImeAction.Default)
    (TextActions.kt:100) and throws otherwise.
  • MUST select the field by
    Modifier.testTag(...)
    whose value is a constant in production code — skydoves hot take #1.
  • MUST route post-input state assertions through
    rule.runOnIdle { … }
    (skydoves hot take #5). The recomposer needs to settle before reading
    TextFieldState.text
    .
  • MUST NOT call
    Thread.sleep
    to wait for IME events. Compose's idle observation includes the text-input pipeline; the assertion will be ready when
    runOnIdle
    returns.
  • MUST NOT simulate text entry by injecting individual
    Key
    events through
    performKeyInput { pressKey(Key.A) }
    unless the test specifically exercises the hardware-keyboard path. The semantics actions are the canonical IME path.
  • PREFERRED: keep
    performTextInputSelection
    calls explicit about
    relativeToOriginalText
    . The default (
    true
    ) is correct for most cases; flip it only when the field installs a
    VisualTransformation
    .
  • 必须使用
    performTextReplacement
    覆盖已有值。不得连续调用两次
    performTextInput
    并期望第二次调用替换第一次的内容——它们会在光标处拼接。
  • 必须在调用
    performImeAction
    前声明非默认的
    ImeAction
    (例如
    KeyboardOptions(imeAction = ImeAction.Next)
    )。该 API 会断言
    !hasImeAction(ImeAction.Default)
    (TextActions.kt:100),否则将抛出异常。
  • 必须使用
    Modifier.testTag(...)
    选择输入框,并且该标签值应为生产代码中的常量——skydoves hot take #1。
  • 必须通过
    rule.runOnIdle { … }
    执行输入操作后的状态断言(skydoves hot take #5)。读取
    TextFieldState.text
    前,需要等待 recomposer 稳定下来。
  • 不得调用
    Thread.sleep
    等待 IME 事件。Compose 的 idle observation 已包含 text-input pipeline;当
    runOnIdle
    返回时,断言所需状态已经就绪。
  • 不得通过
    performKeyInput { pressKey(Key.A) }
    注入单个
    Key
    事件来模拟文本输入,除非测试明确需要验证硬件键盘路径。semantics actions 才是标准的 IME 路径。
  • **推荐:**明确指定
    performTextInputSelection
    调用中的
    relativeToOriginalText
    。大多数情况下应使用默认值(
    true
    );仅当输入框安装了
    VisualTransformation
    时才调整。

Verification

验证

  • Every test that overwrites field content uses
    performTextReplacement(...)
    or
    performTextClearance()
    followed by
    performTextInput(...)
    . No back-to-back
    performTextInput
    calls expecting replacement semantics.
  • Every
    performImeAction
    call targets a field that declares
    KeyboardOptions(imeAction = ImeAction.Next | Done | Search | …)
    in production source.
  • State or text assertions following an input action run inside
    rule.runOnIdle { … }
    .
  • No
    Thread.sleep
    in the test method.
  • ./gradlew :app:connectedDebugAndroidTest
    (or
    :app:testDebugUnitTest
    for Robolectric) passes for the test under change.
  • 每个覆盖输入框内容的测试都使用
    performTextReplacement(...)
    ,或先调用
    performTextClearance()
    再调用
    performTextInput(...)
    。不存在连续调用
    performTextInput
    并期望产生替换语义的情况。
  • 每个
    performImeAction
    调用都指向在生产代码中声明了
    KeyboardOptions(imeAction = ImeAction.Next | Done | Search | …)
    的输入框。
  • 输入 action 后的状态或文本断言均在
    rule.runOnIdle { … }
    中运行。
  • 测试方法中不存在
    Thread.sleep
    。
  • ./gradlew :app:connectedDebugAndroidTest
    (或使用 Robolectric 时执行
    :app:testDebugUnitTest
    )能够通过本次修改涉及的测试。

References

参考资料