如何通过 UI 测试在 Jetpack compose TextField 中输入文本?

时间:2021-03-17 14:45:42

标签: android android-espresso android-jetpack ui-testing android-jetpack-compose

在 Jetpack compose 中,我有一个 TextField,我正在尝试编写 Espresso UI 测试。我没有找到如何在 TextField 中输入文本,请问有什么想法吗?

        TextField(
            value = textState.value,
            modifier = Modifier.fillMaxWidth(),
            onValueChange = {
                textState.value = it
                apiServiceCall(textState.value.text)
            },
            keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences)
        )

@get:Rule
val composeTestRule = createAndroidComposeRule<MainActivity>()

@Test
fun enterTextAndMakeServiceCall() {
    ActivityScenario.launch(MainActivity::class.java)

    //TODO: Enter text inside the TextField
    composeTestRule.onNode(hasText(getString(R.string.result)))
}

1 个答案:

答案 0 :(得分:4)

我首先在我要测试的可组合对象上设置 testTag 修饰符:

const val MY_TEXTFIELD_TAG = "myTextFieldTag"

TextField(
    value = textState.value,
    modifier = Modifier.fillMaxWidth().testTag(MY_TEXTFIELD_TAG),
    onValueChange = {
        textState.value = it
    },
    keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences),
)

然后从您的测试中,您可以像这样设置和检查值:

@Test
fun setAndCheckTheTextFieldValue() {
    ActivityScenario.launch(MainActivity::class.java)
    val resultText = "result"

    // Sets the TextField value
    composeTestRule.onNodeWithTag(MY_TEXTFIELD_TAG).performTextInput(resultText)

    // Asserts the TextField has the corresponding value
    composeTestRule.onNodeWithTag(MY_TEXTFIELD_TAG).assert(hasText(resultText))
}