You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose自动化测试中如何模拟键盘删除按钮操作?

Jetpack Compose 自定义输入框删除键自动化测试方案

在Compose测试中没有直接的performDelete()方法,但可以通过performKeyPress()模拟删除键的按键事件来实现你的测试需求,以下是针对两个场景的具体实现:

场景1:光标左侧有字符时,删除该字符

@get:Rule
val composeTestRule = createComposeRule()

@Test
fun deleteKeyRemovesCharacterWhenLeftExists() {
    // 初始化自定义输入框
    composeTestRule.setContent {
        YourCustomEditText(
            text = remember { mutableStateOf("Hello") },
            onValueChange = { /* 你的回调逻辑 */ }
        )
    }

    // 聚焦输入框,确保能接收键盘事件
    composeTestRule.onNodeWithTag("your-custom-edittext-tag").performClick()
    // 模拟按下删除键(KEYCODE_DEL)
    composeTestRule.onNodeWithTag("your-custom-edittext-tag")
        .performKeyPress(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
    
    // 验证文本变为"Hell"
    composeTestRule.onNodeWithTag("your-custom-edittext-tag")
        .assertTextEquals("Hell")
}

场景2:光标左侧无字符时,文本无变化

@Test
fun deleteKeyDoesNothingWhenNoCharacterLeft() {
    composeTestRule.setContent {
        YourCustomEditText(
            text = remember { mutableStateOf("") }, // 初始为空文本
            onValueChange = { /* 你的回调逻辑 */ }
        )
    }

    composeTestRule.onNodeWithTag("your-custom-edittext-tag").performClick()
    // 多次按下删除键,验证文本仍为空
    repeat(3) {
        composeTestRule.onNodeWithTag("your-custom-edittext-tag")
            .performKeyPress(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
    }

    composeTestRule.onNodeWithTag("your-custom-edittext-tag")
        .assertTextEquals("")
}

// 补充:光标在文本开头的情况
@Test
fun deleteKeyDoesNothingWhenCursorAtStart() {
    composeTestRule.setContent {
        val textState = remember { mutableStateOf("Hello") }
        YourCustomEditText(
            text = textState,
            onValueChange = { textState.value = it },
            // 假设你的自定义输入框支持控制光标位置,这里设置光标在开头
            selection = remember { mutableStateOf(TextRange(0, 0)) }
        )
    }

    composeTestRule.onNodeWithTag("your-custom-edittext-tag").performClick()
    composeTestRule.onNodeWithTag("your-custom-edittext-tag")
        .performKeyPress(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
    
    // 验证文本仍为"Hello"
    composeTestRule.onNodeWithTag("your-custom-edittext-tag")
        .assertTextEquals("Hello")
}

注意事项

  • 确保你的自定义输入框设置了testTag,方便测试时定位节点
  • performKeyPress需要导入androidx.compose.ui.test.performKeyPress和android.view.KeyEvent
  • 如果自定义输入框有特殊的光标控制逻辑,需要确保测试时光标位置符合场景要求

内容的提问来源于stack exchange,提问作者atulgpt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 06:27:33