1 year ago
#374692

Mahozad
Composable does not remember input when changing configuration in test
I'm writing instrumented tests for a Jetpack Compose component. My composable uses rememberSaveable
to remember between configuration changes (activity restarts):
@Composable
fun AddUserScreen() {
Input(
shouldRequestFocus = true,
stringResource(R.string.user_first_name),
stringResource(R.string.user_first_name_label),
tag = "input-first-name"
)
}
@Composable
fun Input(
shouldRequestFocus: Boolean,
text: String,
label: String,
tag: String
) {
var value by rememberSaveable { mutableStateOf("") } // <-- Important part
val focusRequester = FocusRequester()
Row(verticalAlignment = Alignment.CenterVertically) {
Text(text)
Spacer(modifier = Modifier.width(10.dp))
TextField(
value = value,
onValueChange = { value = it },
label = { Text(label) },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
modifier = Modifier
.focusRequester(focusRequester)
.testTag(tag)
)
}
if (shouldRequestFocus) {
DisposableEffect(Unit) {
focusRequester.requestFocus()
onDispose { }
}
}
}
The input value is retained when I open the app myself and rotate the device. But in the following test the input is not retained on configuration change and the test fails:
@get:Rule val composeTestRule = createAndroidComposeRule<AddUserActivity>()
@Test fun whenAConfigChangeHappensTheFirstNameInputShouldRetainItsValue() {
composeTestRule.setContent {
WorkoutLoggerTheme {
AddUserScreen()
}
}
composeTestRule.onNodeWithTag("input-first-name").performTextInput("John")
composeTestRule.activity.requestedOrientation = SCREEN_ORIENTATION_LANDSCAPE
composeTestRule.waitForIdle()
composeTestRule.onNodeWithTag("input-first-name").assertTextEquals("John")
}
android
android-jetpack-compose
ui-testing
instrumented-test
composable
0 Answers
Your Answer