Skip to content
Velloreth
Android Development 8 min read

Testing Compose UI: Practical Strategies

How to test Jetpack Compose screens that do not flake — semantics, state hoisting, synchronization with the v2 test APIs, and where screenshot tests fit.

By

A Compose UI test is three verbs: find a node, act on it, assert on it. The finders query the semantics tree, the same structure that TalkBack and other accessibility services read. That single fact drives most of Compose testing strategy — if a test cannot find an element, the likely problem is not the test, it is that the element does not expose itself to users of assistive technology.

This post covers the mechanics that keep tests stable: the right entry points, state hoisting as a testing pattern, synchronization under the v2 APIs, and how screenshot testing fits next to behavioral tests.

Setup

Two dependencies, plus the test manifest for createComposeRule():

androidTestImplementation("androidx.compose.ui:ui-test-junit4:<version>")
debugImplementation("androidx.compose.ui:ui-test-manifest:<version>")

A minimal test:

class LoginScreenTest {

    @get:Rule
    val composeTestRule = createComposeRule()

    @Test
    fun emptyEmail_showsErrorOnSubmit() {
        composeTestRule.setContent {
            MyAppTheme {
                LoginScreen(state = LoginState(), onSubmit = {})
            }
        }

        composeTestRule.onNodeWithText("Continue").performClick()
        composeTestRule.onNodeWithText("Email is required").assertIsDisplayed()
    }
}

createComposeRule() hosts your content in a ComponentActivity. If you need your own Activity — to read string resources, for example — use createAndroidComposeRule<ComponentActivity>() and call composeTestRule.activity.getString(...), or createAndroidComposeRule<MyActivity>() when the Activity sets its own content.

v1 is deprecated: use the v2 APIs

The entry points you may have seen in older tutorials — androidx.compose.ui.test.junit4.createComposeRule, runComposeUiTest — are v1 and deprecated. The v2 versions live in new packages and change the default dispatcher:

v1v2
androidx.compose.ui.test.junit4.createComposeRuleandroidx.compose.ui.test.junit4.v2.createComposeRule
androidx.compose.ui.test.junit4.createAndroidComposeRuleandroidx.compose.ui.test.junit4.v2.createAndroidComposeRule
androidx.compose.ui.test.runComposeUiTestandroidx.compose.ui.test.v2.runComposeUiTest

v1 used UnconfinedTestDispatcher: a coroutine launched by your UI ran eagerly, often finishing before the next line of test code. v2 uses StandardTestDispatcher, matching runTest everywhere else — coroutines are queued until the clock advances. Most tests that act and assert through the test rule keep working, because waitForIdle() and friends advance the clock. The ones that break have a specific shape: trigger a load, then assert on the very next line with no test-rule call in between. The fix is waitForIdle() or runOnIdle { } before the assertion.

If you combine Compose tests with runTest from kotlinx-coroutines-test, prefer runComposeUiTest — it runs your test block inside its own runTest scope with a synchronized clock, instead of the two-clocks problem you get from pairing createComposeRule() with a separate runTest.

Finding elements: match what the user sees

Finders walk the semantics tree. Prefer the ones that match user perception:

composeTestRule.onNodeWithText("Continue").performClick()
composeTestRule.onNodeWithContentDescription("Close").performClick()
composeTestRule.onNode(hasTestTag("submit_button")).performTouchInput { click() }

onNodeWithText and onNodeWithContentDescription should be your defaults. testTag is a last resort — if a node has neither text nor a content description, that is usually an accessibility gap, not a test problem.

When you cannot find a node, print the tree:

composeTestRule.onRoot().printToLog("SEMANTICS")
// or, for the unmerged tree:
composeTestRule.onRoot(useUnmergedTree = true).printToLog("SEMANTICS_UNMERGED")

This shows exactly what properties each node exposes. A classic case from the Compose testing codelab: tabs that set clearAndSetSemantics { contentDescription = ... } expose a content description, not the Text child’s label — so onNodeWithText("ACCOUNTS") fails while onNodeWithContentDescription("Accounts") succeeds.

The merged versus unmerged tree matters here. Compose merges descendants into parents where it makes sense for accessibility — a Button with a Text inside becomes one node. Most tests query the merged tree (the default). Pass useUnmergedTree = true when you need to reach inside a merged component, for example to assert that a specific child Text exists:

composeTestRule.onNode(
    hasText("ACCOUNTS") and hasParent(hasContentDescription("Accounts")),
    useUnmergedTree = true
).assertExists()

Actions and assertions

Actions inject user events: performClick, performTextInput, performScrollTo, performTouchInput { swipeUp() }. You cannot chain actions inside one perform call — make separate calls.

Assertions verify state: assertIsDisplayed, assertIsNotDisplayed, assertIsEnabled, assertIsSelected, assertTextEquals, assertTextContains, assertContentDescriptionEquals. Collections get assertCountEquals, assertAny, assertAll. For anything else, assert(hasX(...)) with a SemanticsMatcher works, and matchers compose with and / or:

composeTestRule
    .onAllNodes(hasClickAction() and hasAnyAncestor(hasTestTag("player_list")))
    .assertCountEquals(4)

State hoisting is a testing pattern

The cheapest way to test every state of a screen is to make the screen a function of its state. Hoist the state: the screen composable takes a state object and callbacks, and a thin wrapper connects it to the ViewModel:

sealed interface ProfileUiState {
    data object Loading : ProfileUiState
    data class Loaded(val name: String, val bio: String) : ProfileUiState
    data class Error(val message: String) : ProfileUiState
}

@Composable
fun ProfileScreen(
    state: ProfileUiState,
    onRetry: () -> Unit,
    modifier: Modifier = Modifier
) {
    when (state) {
        ProfileUiState.Loading -> ProfileLoading()
        is ProfileUiState.Loaded -> ProfileContent(state)
        is ProfileUiState.Error -> ProfileError(state.message, onRetry)
    }
}

Now every state is one test, with no fake ViewModel, no repository, and no coroutine:

@Test
fun errorState_showsRetryButton() {
    composeTestRule.setContent {
        ProfileScreen(
            state = ProfileUiState.Error("Network unavailable"),
            onRetry = {}
        )
    }
    composeTestRule.onNodeWithText("Network unavailable").assertIsDisplayed()
    composeTestRule.onNodeWithText("Retry").assertIsClickable()
}

The ViewModel still gets tested — as a plain JVM unit test with a fake repository, where it belongs. UI tests should not re-test logic; they should verify that each state renders and that user interactions call the right callbacks:

@Test
fun retryClicks_invokesCallback() {
    var retried = false
    composeTestRule.setContent {
        ProfileScreen(
            state = ProfileUiState.Error("Boom"),
            onRetry = { retried = true }
        )
    }
    composeTestRule.onNodeWithText("Retry").performClick()
    assertTrue(retried)
}

This also covers the full app path once or twice — a smoke test that launches the real app, signs in with a fake backend, and walks one happy path. But the bulk of coverage should be small screen-state tests, because they are fast, deterministic, and easy to debug when they fail.

Synchronization: never sleep

Compose tests are synchronized with the composition by default: a finder or assertion waits until the UI is idle before running. Animations and recompositions are handled. What synchronization does not cover is work Compose cannot see — a ViewModel coroutine fetching from a repository, a delayed state update, anything outside the composition.

For those, use waitUntil with a real condition:

composeTestRule.waitUntil(timeoutMillis = 5_000) {
    composeTestRule
        .onAllNodesWithText("Loaded")
        .fetchSemanticsNodes()
        .isNotEmpty()
}

There are helpers for common cases — waitUntilExactlyOneExists, for instance. The v2 APIs queue coroutines, so the pattern for a screen that loads on launch is: setContent, then waitForIdle() or waitUntil { condition } before asserting. Never Thread.sleep; it wastes time on fast runs and fails on slow CI machines.

If you have a subsystem the test should track — a background image loader, a custom scheduler — Compose has an idling resource API similar to Espresso’s. Use it for the subsystem; use waitUntil for a one-off condition.

Interop and edge cases

A few situations that come up in real apps:

Testing with Views in the same screen. Compose interops with Views; createEmptyComposeRule() (v2 package) gives you Compose testing APIs without hosting an Activity, for tests that already have an Espresso rule driving the rest of the screen.

Custom semantics. When a composable exposes information tests need but does not render as text — a date picker’s selected value, a chart’s data point — define a custom SemanticsPropertyKey, set it with the semantics modifier, and assert with SemanticsMatcher.expectValue. This is better than test tags when the information is a real property of the component.

Focus and keyboard. The v2 APIs enforce InputMode.Touch at the start of each test for determinism. For focus tests, pass ComposeUiTestConfig(inputMode = InputMode.Keyboard) when creating the rule.

Lists and scrolling. Before acting on an item that may be off-screen, performScrollTo() on the node, or scroll a parent with performScrollToNode(hasText(...)). Lazy lists do not compose off-screen children, so the node genuinely does not exist until you scroll.

The common thread: whatever the user can do, the test can do — find, act, assert — and whatever the user cannot perceive, the test should not depend on.

Where screenshot tests fit

Behavioral assertions answer “does this state show the right things and call the right callbacks.” They are bad at “is the padding 16dp,” “does dark theme invert correctly,” and “did this font change break the layout.” Screenshot tests fill that gap.

Two routes:

  • Official: the Compose Preview Screenshot testing tool renders your @Preview functions and diffs them against golden images in CI.
  • Roborazzi: captures from ordinary Compose tests on the JVM via Robolectric, with @GraphicsMode(GraphicsMode.Mode.NATIVE). Better when you want a screenshot at a specific point in an interaction, not just a static preview.

The workflow is record, verify, compare: recordRoborazziDebug writes golden images; verifyRoborazziDebug fails the build on any pixel difference; compareRoborazziDebug produces diff images for review without failing. One test per theme or configuration — do not call setContent twice inside one test.

Screenshot tests catch the visual regressions that slip through behavioral tests: a color token change, a spacing tweak in a shared component, a dark-theme contrast bug. They are slow and brittle to overuse, so scope them to shared components and the most important screens, not every composable in the app.

A shape that scales

The strategy that holds up as the app grows:

  1. Unit tests for ViewModels, repositories, and mappers — JVM, milliseconds, high coverage.
  2. Small Compose tests per screen state and interaction — hoisted state, no fake ViewModel, finders on text and content descriptions.
  3. A few journey tests that walk real flows through the app — one or two happy paths, maybe one recovery path.
  4. Screenshot tests for shared components and visual baselines — light and dark, phone and tablet widths.
  5. Accessibility checks in the same Compose tests — if onNodeWithText finds it, TalkBack finds it; that is not a coincidence.

Android’s own guidance says most apps should have many small tests and relatively few big ones: small tests are fast and reliable; big tests have more fidelity but more complex, fragile setups. Compose makes the small tests cheap — a screen state is a data constructor, and a test is a setContent plus three lines. Use that.

Frequently asked questions

What is the difference between the merged and unmerged semantics tree?
The merged tree collapses parents and children into single nodes — a Button appears as one node with its text, not a container plus a Text child. The unmerged tree keeps every node. Most tests should query the merged tree; pass useUnmergedTree = true when you need to reach inside a merged component.
Why does my Compose test fail only on CI?
Usually synchronization: the test asserted before a coroutine or animation finished. Use waitForIdle or waitUntil with a real condition, never Thread.sleep. The v2 APIs queue coroutines, so an assertion immediately after triggering load can run before the load completes.
Should I test ViewModel logic in Compose UI tests?
No. Test ViewModels as plain JVM unit tests with a fake repository, and test screens as Compose tests with states passed directly. That split keeps UI tests fast and avoids duplicating logic coverage.
When should I use screenshot tests?
For visual attributes — spacing, typography, colors, dark theme — which are expensive to assert through the semantics tree. Use the official Compose Preview Screenshot testing tool or Roborazzi; keep behavioral assertions in regular UI tests.