我首先在我要测试的可组合对象上设置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))
}
更新:
我最近使用的另一种方法是改用contentDescription。
假设您有一个 TextField,其内容描述与此类似(为简单起见,此示例未使用状态提升):
@Composable
fun MyTextField() {
val textState = remember { mutableStateOf(TextFieldValue()) }
val textFieldContentDescription = stringResource(id = R.string.text_field_content_description)
TextField(
value = textState.value,
modifier = Modifier
.fillMaxWidth()
.semantics { contentDescription = textFieldContentDescription },
onValueChange = {
textState.value = it
},
)
}
测试可能是这样的:
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun setAndCheckTheTextFieldValue() {
lateinit var textFieldContentDescription: String
composeTestRule.setContent {
textFieldContentDescription = stringResource(id = R.string.text_field_content_description)
MaterialTheme {
MyTextField()
}
}
val resultText = "result"
// Sets the TextField value
composeTestRule.onNodeWithContentDescription(textFieldContentDescription).performTextInput(resultText)
// Asserts the TextField has the corresponding value
composeTestRule.onNodeWithContentDescription(textFieldContentDescription).assert(hasText(resultText, ignoreCase = true))
}
这样,通过内容描述,应用程序也更易于访问。