Skip to content
Tutorials Center
My learning

Topics

Lesson 82 of 104 ยท Testing

Testing Compose UI

Test Jetpack Compose screens with createComposeRule: the semantics tree, finders, assertions, actions, test tags, synchronization and a screenshot testing overview.

A ViewModel test checks that the state is right. A Compose UI test checks the other half: given that state, does the screen show the right things, and when the user taps, does the right thing happen? Compose makes this pleasant, because tests do not look at pixels or at a view hierarchy. They look at the semantics tree: a description of what the UI means (text, buttons, enabled or not, selected or not) which Compose builds for accessibility services such as TalkBack. The same tree that helps a blind user navigate your app helps your tests find a button.

The real Compose test API needs an emulator or Robolectric, and the site has neither, so all real test code here is read-only. The TryIts are plain Kotlin stand-ins on Piston: a small semantics tree with the same kinds of finders, assertions and actions, so you can see how they work inside. They are a teaching model, not the real library. This lesson builds on ViewModel testing, state hoisting and accessibility basics in text and images.

Setup and the first test

Compose UI tests are usually instrumented tests in app/src/androidTest (they run on a device or emulator). With Robolectric they can also run on the JVM in src/test, which is faster but not a real device.

Kotlin
// read-only: app/build.gradle.kts
dependencies {
    androidTestImplementation(platform(libs.androidx.compose.bom))
    androidTestImplementation("androidx.compose.ui:ui-test-junit4")
    debugImplementation("androidx.compose.ui:ui-test-manifest")   // registers the test Activity
}

The central object is the compose rule. createComposeRule() starts an empty host activity; you call setContent with the UI under test, then find, assert and act:

Kotlin
// read-only
class CounterScreenTest {

    @get:Rule
    val composeTestRule = createComposeRule()

    @Test
    fun tappingIncrement_updatesTheLabel() {
        composeTestRule.setContent {
            AppTheme { CounterRoute() }
        }

        composeTestRule.onNodeWithText("Count: 0").assertIsDisplayed()

        composeTestRule.onNodeWithContentDescription("Increment").performClick()

        composeTestRule.onNodeWithText("Count: 1").assertIsDisplayed()
    }
}

If the test needs the real activity (for string resources through activity.getString(...), or to test navigation), use createAndroidComposeRule<MainActivity>().

The semantics tree

Every composable that matters to accessibility adds a semantics node carrying properties: Text (a list of strings), ContentDescription, Role, Disabled, Selected, ToggleableState, click actions and more. A Button provides a role and a click action; a Text provides its text; Modifier.semantics { ... } adds or overrides properties on your own composables.

Compose also merges nodes by default. A Button containing a Text("Add") is one node for TalkBack (it reads "Add, button"), not two, so the merged tree has a single node with the text Add and a click action. The tree where each composable keeps its own node is the unmerged tree. Finders search the merged tree unless you pass useUnmergedTree = true, which you need only when you want a specific child inside a merged parent.

flowchart TD
    subgraph U["Unmerged tree"]
        UB["Button<br/>click action"] --> UT["Text 'Add'"]
    end
    subgraph M["Merged tree (default for finders)"]
        MB["Node: role Button<br/>text 'Add', click action"]
    end
    U -- "mergeDescendants" --> M

A Button merges its children into one accessibility node. Finders see the merged node by default.

You can print the tree during a test to see what your finders can see: composeTestRule.onRoot().printToLog("TAG") writes it to Logcat (see Running, Debugging and Logcat). It is the first thing to try when a finder does not find what you expect.

Finders, assertions and actions

A test line has three parts: finder (which node), then an assertion (check a property) or an action (do something).

Kind Examples
Finders onNodeWithText("Save"), onNodeWithContentDescription("Close"), onNodeWithTag("cart"), onAllNodesWithText("Item"), onNode(hasText("Save") and hasClickAction()), onRoot()
Matchers hasText, hasContentDescription, hasTestTag, hasClickAction, isEnabled, isToggleable, isSelected, hasAnyChild, hasParent, combined with and, or, not
Assertions assertExists, assertDoesNotExist, assertIsDisplayed, assertIsEnabled, assertIsNotEnabled, assertTextEquals, assertIsOn, assertIsSelected
Actions performClick, performTextInput, performTextReplacement, performImeAction, performScrollTo, performScrollToIndex, performTouchInput { swipeUp() }

Two details trip up beginners. onNode... finders require exactly one match, and fail with a message about the number found otherwise; use onAllNodes... and [index] or a narrower matcher when several nodes legitimately match. And assertExists means "in the semantics tree", while assertIsDisplayed also requires the node to be visible on screen: an item far down a LazyColumn does not exist at all until it is composed, so scroll to it first with performScrollToIndex.

The first TryIt models the tree and the finders. It builds a small "cart" screen as a tree of nodes, prints the unmerged and merged views, then runs finders, assertions and a click. Each failing finder prints the kind of message you would get from the real library.

Kotlin A semantics tree with finders (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Look at the output. In the merged tree each Button is a single node whose text came from its Text child, which is why onNodeWithText("Add") finds the button and a click on it works. With the unmerged tree the same finder reaches the inner text. The last three tests fail on purpose, with messages in the style of the real library: a disabled button, an ambiguous finder (two clickable nodes) and a node that does not exist.

Test tags and good finders

Which finder should you prefer? Think about what the user perceives:

  1. Text and content descriptions first. onNodeWithText("Sign in") checks what the user reads, and onNodeWithContentDescription("Close") also confirms that the icon button has an accessible name. A test that cannot find the button this way tells you a TalkBack user cannot either.
  2. Test tags when there is no good user-facing handle: a list container, a container whose text changes, or two identical labels. Add them with Modifier.testTag("cart_list") and keep the tag strings in a shared constant, so the app and the tests cannot drift apart.
  3. Avoid finding by position or by implementation details. onAllNodes(...)[2] breaks when someone inserts a row.

Do not put test tags on everything. Tags do not help accessibility and add noise; use them where they pay for themselves.

For strings from resources, do not hard-code English text in tests that also run in other locales. Read it through the activity (composeTestRule.activity.getString(R.string.save)) or assert on tags and descriptions.

Synchronization: no sleeping

Compose tests are synchronized with the UI: before every finder, assertion and action, the rule waits until the UI is idle: recomposition has finished and pending layout and measure passes are done. You rarely need Thread.sleep, and you should never add one. The rule also controls the animation clock: composeTestRule.mainClock.autoAdvance = false lets you step animations manually with mainClock.advanceTimeBy(300), much like virtual time for coroutines. See Animation in Compose.

What the rule does not know about is your own asynchronous work, for example a coroutine on a real Dispatchers.IO or a network call. For those you have two choices: inject test dispatchers or fake data sources so the work is deterministic (the better option), or wait explicitly with composeTestRule.waitUntil(timeoutMillis = 3_000) { ... }, a condition-based wait that returns as soon as the condition is true.

Test the stateless screen

The easiest screens to test are the ones with hoisted state (see State Hoisting). A stateless composable takes plain data and callbacks, so a test passes in exactly the state it wants and checks the callbacks, with no ViewModel, repository or Hilt in sight:

Kotlin
// read-only
@Composable
fun CounterScreen(count: Int, onIncrement: () -> Unit) {
    Column {
        Text("Count: $count")
        Button(onClick = onIncrement) { Text("Increment") }
    }
}

@Test
fun incrementButton_callsTheCallback() {
    var clicks = 0
    composeTestRule.setContent { CounterScreen(count = 5, onIncrement = { clicks++ }) }

    composeTestRule.onNodeWithText("Count: 5").assertIsDisplayed()
    composeTestRule.onNodeWithText("Increment").performClick()

    assertEquals(1, clicks)
}

This split gives you a good test pyramid for UI: many fast tests of stateless screens with fixed state (loading, empty, error, content), the ViewModel tested separately with fakes (previous lesson), and a few end-to-end tests with the real wiring (Instrumented, Room and Navigation Tests).

The second TryIt shows both sides: a stateless screen tested with fixed state and a click callback, and a small stateful wrapper where the click really changes the state and the screen is rebuilt, as recomposition does.

Kotlin Stateless screens and recomposition after a click (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The third test in that example fails on purpose, to show the message you get when you click a node that has no click action.

Screenshot testing: a short overview

Semantic tests check what is on screen but not how it looks. A wrong color, a clipped label or a broken dark theme passes every semantics assertion. Screenshot testing (also called golden-image testing) renders a composable, saves the image as a golden reference, and in later runs fails if the new rendering differs from it. The workflow is:

  1. Write a test or a @Preview function for each state worth protecting (empty, error, dark theme, large font, right-to-left).
  2. Run the tool in "record" mode once to create the golden images, and review and commit them.
  3. In CI, run in "verify" mode. A failure produces a diff image, and you decide: bug, or intended change that needs new goldens.

Several tools do this, such as Paparazzi and Roborazzi (rendering on the JVM, no device) and Google's Compose Preview Screenshot Testing plugin (built on @Preview functions); check their documentation for current setup. Keep screenshot tests few and focused: they are sensitive to fonts, rendering differences between machines and animations, so freeze animations, use fixed data and render in the same environment each time. Screenshots complement semantic tests; they do not replace them.

Common mistakes

  • Thread.sleep to wait for the UI. The rule synchronizes for you; use waitUntil for your own async work.
  • Finding nodes by index, which breaks when the layout changes.
  • Asserting on hard-coded English strings in tests that may run under other locales.
  • Tagging every composable with testTag instead of using text and descriptions first.
  • Using assertExists when you mean assertIsDisplayed, or the reverse; lazy items do not exist until composed.
  • Forgetting useUnmergedTree = true when a finder must reach a child inside a merging parent.
  • Testing the whole app through the UI for every case. Test states with stateless screens; keep end-to-end tests few.
  • Too many screenshot tests, which become noisy and are updated without being reviewed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What do Compose UI tests inspect to find and check elements?

    Compose builds a semantics tree (text, roles, states, actions) for accessibility. The test finders, assertions and actions work on that tree.
  2. 2. A Button contains Text('Add'). Which finder, with default settings, returns the Button node?

    The Button merges its descendants, so the merged tree (used by default) has one node with the text 'Add' and the click action. The unmerged option would reach the inner Text.
  3. 3. A finder like onNode(hasClickAction()) fails in a screen with two buttons. Why?

    onNode finders must match exactly one node. Use a narrower matcher, a test tag, or onAllNodes with an index when several nodes match.
  4. 4. How should a test wait for the UI to settle after performClick?

    The rule synchronizes with recomposition and layout automatically. Only your own asynchronous work (real dispatchers, network) needs fakes or waitUntil.
  5. 5. What problem does screenshot testing solve that semantics assertions do not?

    Semantics tests verify content and behavior; a golden-image comparison catches how the UI looks, including theme and layout changes.

Summary

  • Compose UI tests use a compose rule (createComposeRule) and work on the semantics tree: finder, then assertion or action.
  • The default tree is merged (a Button is one node); use useUnmergedTree = true to reach a child, and printToLog to see the tree.
  • Prefer finders by text and content description, which double as accessibility checks; add testTag only where needed, from shared constants.
  • onNode... needs exactly one match; assertExists is not the same as assertIsDisplayed, and lazy items must be scrolled into view.
  • The rule waits for idle automatically; control animation time with mainClock and wait for your own async work with fakes or waitUntil.
  • Stateless screens with hoisted state are the easiest to test; add a few end-to-end tests and a few screenshot tests for visuals.
  • The real test API is read-only here; the TryIts are a plain-Kotlin model of the semantics tree and finders.

Next: Instrumented, Room and Navigation Tests