Android Compose: testing button click

Andres Sandoval
2 min readAug 29, 2022

I’m learning how to write a Compose test. The goal: is to show basic test to click a button. Series will show run Compose test using Firebase Test Lab.

  1. Using Android Studio Chipmunk create a new Android project “Compose Activity”. Add below snippet to your MainActivity
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

setContent {
val context = LocalContext.current

ComposeUITestTheme {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.background(Color.White)
) {
Button(
onClick = {
Toast.makeText(context, "Hello world", Toast.LENGTH_SHORT).show()
},
modifier = Modifier.testTag("yourTestTag")
) {
Text(text = stringResource(R.string.click))
}
}
}
}
}
}

2. The new project already comes with the Gradle dependencies for Compose UI testing

androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"

debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_version"

3. Create new test class TestButton. Add below code snippet and import dependencies.

class TestButton {
@get:Rule
val composeTestRule = createAndroidComposeRule(MainActivity::class.java)

@Test
fun testButtonClick() {
val button = composeTestRule.onNode(hasTestTag("yourTestTag"), useUnmergedTree = true)
button.assertIsDisplayed()
button.performClick()
}
}

4. Run test. The test is going to click the button and the toast is going to show.

Thanks for reading.

-Andres

References:

Compose testing Google documentation: https://developer.android.com/jetpack/compose/testing

Hello world test: https://dmytroshuba.com/blog/jetpack-compose-ui-testing/

More advance compose Code lab: https://developer.android.com/codelabs/jetpack-compose-testing

--

--