Compose UI tests
Why it matters
- Compose UI tests are the main automated way to check that a composable renders, responds to input, and switches between states correctly.
- They catch regressions in conditional rendering, state-driven visibility, and input handling that ViewModel tests cannot see.
- Interviewers probe the semantics tree, merged vs unmerged trees, and synchronization (
waitUntil, the test clock, idling) to separate mid from senior candidates. - The same test code can run on a device or emulator, or on the JVM with Robolectric, so you can choose between realism and speed.
The simple explanation
- Testing a restaurant by its printed menu, not by walking into the kitchen.
- You order "pasta" (
onNodeWithText), not "station 3, recipe 7" (internal state). - If the kitchen reorganises, the menu stays the same, so your test still works.
- A combo plate (
mergeDescendants = true) is listed as one item; to see its parts you ask for the full ingredient list (useUnmergedTree = true). - The waiter (the test rule) only sees the menu, never the kitchen layout.
Compose UI tests use JUnit 4 and a compose test rule:
createComposeRule()gives you a blank host activity; you supply the UI withrule.setContent { }. On Android it needsandroidx.compose.ui:ui-test-manifest(usually asdebugImplementation) so that activity exists.createAndroidComposeRule<MainActivity>()launches your real activity and gives access to it throughrule.activity, for example to read string resources.- In recent Compose versions both rules come from the
androidx.compose.ui.test.junit4.v2package. The olderandroidx.compose.ui.test.junit4versions are deprecated: they ran composition coroutines on anUnconfinedTestDispatcher, while v2 uses aStandardTestDispatcher, likerunTest.
They usually live in src/androidTest and run on a device or emulator. The same tests can also run as local tests in src/test with Robolectric (@RunWith(AndroidJUnit4::class)), which is much faster but does not draw on real hardware.
Tests interact with the semantics tree, the same information accessibility services use. Each composable can contribute semantics such as text, content description, role, click actions, and test tags. You find nodes with finders:
| Finder | Finds by |
|---|---|
onNodeWithText("Label") | Text, including merged text of a parent |
onNodeWithTag("my_btn") | Modifier.testTag("my_btn") |
onNodeWithContentDescription("desc") | Accessibility label |
onAllNodesWithText("x") | Every matching node, as a collection |
onNode(hasText("x") and hasClickAction()) | Any combination of matchers |
The returned SemanticsNodeInteraction supports actions (performClick(), performTextInput("text"), performTextReplacement("text"), performScrollTo()) and assertions (assertIsDisplayed(), assertTextEquals("x"), assertIsEnabled(), assertDoesNotExist()).
Merged vs unmerged tree. By default, finders search the merged tree. Components like Button and anything with Modifier.semantics(mergeDescendants = true) or Modifier.clickable merge their children into one node. In that node the children's texts are combined, but their test tags are not, so onNodeWithTag("child_tag") fails and onNodeWithText("Child") finds the parent. Pass useUnmergedTree = true to reach the child itself. rule.onRoot().printToLog("TAG") prints the tree when a finder surprises you.
Synchronization. The rule waits for Compose to be idle (no pending recomposition, layout, or animation frames) before each finder and assertion, using a virtual test clock (rule.mainClock). Work it cannot see, such as a real network call on another thread, needs rule.waitUntil(timeoutMillis) { condition }, where the lambda returns a Boolean, or a registered Espresso IdlingResource. Thread.sleep guesses a duration and is never the right tool.
Notes
- Compose UI tests use JUnit 4 and a rule annotated with
@get:Rule. They usually live insrc/androidTest; with Robolectric they can run insrc/teston the JVM. createComposeRule()hosts content you pass tosetContent;createAndroidComposeRule<YourActivity>()launches a real activity and exposesrule.activity.- All finders search the semantics tree, merged by default. Pass
useUnmergedTree = trueto reach a child inside a merged node. onNodeWithTextandonNodeWithTagfail if zero or more than one node matches. UseonAllNodesWithTextandfetchSemanticsNodes().sizewhen you expect several.performTextInputtypes text at the cursor, so existing text stays. UseperformTextReplacementto replace it orperformTextClearanceto clear it.assertDoesNotExist()checks that a node is not in the tree at all;assertIsNotDisplayed()checks a node that exists but is not visible on screen.waitUntil(timeoutMillis) { ... }takes a lambda that returnsBoolean; the default timeout is 1 second. Helpers likewaitUntilExactlyOneExists(hasText("Done"))wrap the common cases.rule.mainClock.advanceTimeBy(ms)moves the test clock, which also drivesdelayinside aLaunchedEffect. SetmainClock.autoAdvance = falsefirst to stop the rule advancing it for you, for example to check an animation frame by frame.testTagdoes not change with language or copy edits. Text finders do, so read the text from the same string resource in the test when you use them.performScrollTo()scrolls the node's scrollable parents until it is visible; for an item aLazyColumnhas not composed yet, callperformScrollToNode(hasText("..."))on the list itself.
Code example
This test drives a minimal login form: it clicks the button with no input to show an error, then types a valid email and clicks again to confirm the error disappears. It runs on a device from src/androidTest; to run it under Robolectric in src/test, add @RunWith(AndroidJUnit4::class) to the class.
package com.example.app
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertTextEquals
import androidx.compose.ui.test.junit4.v2.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTextInput
import org.junit.Rule
import org.junit.Test
@Composable
fun LoginForm() {
var email by remember { mutableStateOf("") }
var error by remember { mutableStateOf<String?>(null) }
Column {
OutlinedTextField(
value = email,
onValueChange = { email = it },
label = { Text("Email") },
modifier = Modifier.testTag("email_field"),
)
Button(onClick = { error = if (email.isBlank()) "Email is required" else null }) {
Text("Sign in")
}
error?.let { Text(it, modifier = Modifier.testTag("error_text")) }
}
}
class LoginFormTest {
@get:Rule
val rule = createComposeRule()
// Plain names: spaces in method names are not allowed in DEX before API 30
@Test
fun blankEmail_showsError_validEmail_clearsIt() {
rule.setContent { LoginForm() }
// No input: the click should show the error
rule.onNodeWithText("Sign in").performClick()
rule.onNodeWithTag("error_text")
.assertIsDisplayed()
.assertTextEquals("Email is required")
// Type an email and click again: the error must disappear
rule.onNodeWithTag("email_field").performTextInput("user@example.com")
rule.onNodeWithText("Sign in").performClick()
rule.onNodeWithTag("error_text").assertDoesNotExist()
}
}Buttonmerges its content, soonNodeWithText("Sign in")finds the clickable button node itself, which is whatperformClickneeds.- The field starts empty, so
performTextInputleaves exactlyuser@example.comin it; with existing text it would type after it. - No waiting code is needed: state changes trigger recomposition, and the rule waits for Compose to be idle before each finder and assertion.
- In a real app, test the stateless composable (state and callbacks passed in) or the screen with a fake ViewModel, so the test controls the data.
Run the idea in plain Kotlin
A tiny model of a merged semantics tree: a button merges its child text, the merged node collects the text but not the child's tag, and the unmerged search still sees the child.
data class Node(
val tag: String? = null,
val text: String? = null,
val mergeDescendants: Boolean = false,
val children: List<Node> = emptyList(),
)
// What a finder sees: flattened nodes, merged or not
data class Visible(val tag: String?, val texts: List<String>)
fun allTexts(node: Node): List<String> = listOfNotNull(node.text) + node.children.flatMap { allTexts(it) }
fun flatten(node: Node, merged: Boolean): List<Visible> =
if (merged && node.mergeDescendants) {
// Text is merged up; children's tags are not
listOf(Visible(node.tag, allTexts(node)))
} else {
listOf(Visible(node.tag, listOfNotNull(node.text))) + node.children.flatMap { flatten(it, merged) }
}
fun findByTag(root: Node, tag: String, useUnmergedTree: Boolean = false): String {
val hits = flatten(root, merged = !useUnmergedTree).filter { it.tag == tag }
return if (hits.size == 1) "found " + hits[0].texts else "no node with tag '" + tag + "'"
}
fun findByText(root: Node, text: String): String {
val hits = flatten(root, merged = true).filter { text in it.texts }
return if (hits.size == 1) "found node tag=" + hits[0].tag + " texts=" + hits[0].texts else "found " + hits.size
}
fun main() {
val screen = Node(
tag = "root",
children = listOf(
Node(tag = "price_card", mergeDescendants = true, children = listOf(
Node(tag = "title", text = "Coffee"),
Node(tag = "price", text = "3.50"),
)),
),
)
println("onNodeWithTag(price): " + findByTag(screen, "price"))
println("onNodeWithTag(price, useUnmergedTree = true): " + findByTag(screen, "price", useUnmergedTree = true))
println("onNodeWithTag(price_card): " + findByTag(screen, "price_card"))
println("onNodeWithText(3.50): " + findByText(screen, "3.50"))
}Expected output:
onNodeWithTag(price): no node with tag 'price'
onNodeWithTag(price, useUnmergedTree = true): found [3.50]
onNodeWithTag(price_card): found [Coffee, 3.50]
onNodeWithText(3.50): found node tag=price_card texts=[Coffee, 3.50]
In production
- A developer added
Modifier.semantics(mergeDescendants = true)to a product card so TalkBack reads it as one item, as an accessibility audit had asked. - Tests that called
onNodeWithTag("price")on aTextinside the card started failing with "could not find any node" in CI. - Nobody connected the accessibility change to the test failures, so the build stayed red for most of a day.
- Tests that check what the user hears now assert on the merged card node:
onNodeWithTag("product_card").assertTextContains("3.50"). - Tests that really need the child pass
useUnmergedTree = true. - The failing tests' logs now include
onRoot().printToLog("UI")output on failure, which made the merged node obvious.
- A test asserted that a loading spinner disappeared after a call to a local test server.
- It used
Thread.sleep(2000)before the assertion, which was sometimes not enough on slower CI emulators. - The failure was intermittent, so the team kept re-running the job.
- The sleep was replaced with
rule.waitUntil(timeoutMillis = 10_000) { rule.onAllNodesWithTag("content").fetchSemanticsNodes().isNotEmpty() }, which returns as soon as the content appears. - The screen's data source was then replaced in tests with a fake repository, so the test no longer waits on a server at all.
- Code review now rejects
Thread.sleepin UI tests.
Common mistakes
- Using Thread.sleep to wait. It guesses a duration: too short is flaky, too long is slow. The rule already waits for Compose to be idle; for other async work use
waitUntilwith a condition, or anIdlingResource. - Putting an assertion inside waitUntil. The lambda must return
Boolean; a failing assertion throws straight out instead of being retried. CheckonAllNodesWithTag(...).fetchSemanticsNodes().isNotEmpty()or usewaitUntilExactlyOneExists. - Expecting performTextInput to replace text. It types at the cursor, so the old text stays. Use
performTextReplacementorperformTextClearancefirst. - Forgetting the merged tree. A child's test tag inside a
Buttonor amergeDescendantsparent is not in the merged tree. PassuseUnmergedTree = true, or assert on the merged parent. - Hard-coding visible strings. A copy change or a different device language breaks the test. Use a
testTag, or load the text from the same string resource, for example throughrule.activity.getString(R.string.sign_in)withcreateAndroidComposeRule. - Using @Rule instead of @get:Rule in Kotlin. JUnit needs the annotation on the getter; on the field it fails with "The @Rule 'rule' must be public".
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How does Compose UI testing differ from Espresso?”
“What is the semantics tree and why does it matter for tests?”
“How do you test async UI updates in Compose?”
“When should you use testTag versus onNodeWithText?”
Quiz
You want a Compose UI test to run as a fast local test in src/test. What do you need?
A Row has Modifier.semantics(mergeDescendants = true), and a Text inside it has testTag("price"). What does rule.onNodeWithTag("price").assertExists() do?
Which is a correct way to wait for content that a background call adds to the screen?
A text field already contains "user". What does performTextInput("@example.com") leave in it?
0 of 4 answered
Mini task
Exercise: Test a counter composable with Compose UI tests (15 min)
- In
src/androidTest, create a classCounterScreenTestwith@get:Rule val rule = createComposeRule(). - Write a
CounterScreencomposable with aTextshowing a count (Modifier.testTag("count_text")) and aButtonlabelled "Increment", inside aColumn. - Test
initialCount_isZero: before any click, assertrule.onNodeWithTag("count_text").assertTextEquals("0"). - Test
threeClicks_showThree: callrule.onNodeWithText("Increment").performClick()three times, then assert the count text is"3". - Test
delayedIncrement_appearsAfterDelay: add aLaunchedEffect(Unit) { delay(500); count++ }. AftersetContent, assert"0", callrule.mainClock.advanceTimeBy(500 + 16)(the delay plus one frame), then assert"1". - Run
./gradlew connectedDebugAndroidTeston a device or emulator.
Done condition: all three tests pass, method names contain no spaces, and no test uses Thread.sleep.