Build: Greeting Screen
A simple screen that shows a greeting message and a button to change the greeting.
Target UI
--------------------- | Greeting Screen | |-------------------| | Hello, User! | | | | [Change Greeting] | ---------------------
--------------------- | Greeting Screen | |-------------------| | Hello, User! | | | | [Change Greeting] | ---------------------
import androidx.compose.foundation.layout.Column import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier @Composable fun GreetingScreen() { // TODO: Add state and UI here }
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.unit.dp @Composable fun GreetingScreen() { var greeting by remember { mutableStateOf("Hello, User!") } Column(modifier = Modifier.padding(16.dp)) { Text( text = greeting, modifier = Modifier.testTag("greetingText") ) Button( onClick = { greeting = "Welcome to Compose UI Testing!" }, modifier = Modifier.testTag("changeGreetingButton") ) { Text("Change Greeting") } } }
We use remember and mutableStateOf to hold the greeting text state. The Text composable shows the current greeting. The Button updates the greeting when clicked. We add testTag modifiers to identify UI elements in tests easily.
--------------------- | Greeting Screen | |-------------------| | Hello, User! | | | | [Change Greeting] | ---------------------
createComposeRule() in Compose UI testing?createComposeRule()onNodeWithText().findViewByText, getElementByText, and selectNode do not exist in Compose testing.composeTestRule.setContent {
Text("Welcome")
}
composeTestRule.onNodeWithText("Welcome").assertExists()
What will happen when this test runs?Text composable with the string "Welcome".assertExists() checks that the node with text "Welcome" is present, which it is.composeTestRule.setContent {
Button(onClick = {}) {
Text("Click Me")
}
}
composeTestRule.onNodeWithTag("button").performClick()Modifier.testTag("button") applied, which is missing.onNodeWithTag("item_3") to find the node by its unique test tag.assertIsDisplayed() confirms the node is visible, and performClick() simulates a click.assertExists() alone doesn't check visibility.Pass the test and this pattern moves unknown