在 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)))
}
答案 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))
}