skip to content

In a Jetpack Compose UI test using the v2 createComposeRule, how do you find a node by text or test tag, click it and assert?

level: juniorimportance: must knowfreq 72%

answer

  1. semantics tree, not View ids
  2. rule factory from the v2 package
  3. setContent once, then onNodeWith...
  4. perform..., then assert...
  5. zero or two matches throw AssertionError

basics

~10 s

Create the rule with the v2 createComposeRule, call setContent once, find a node with onNodeWithText or onNodeWithTag (the tag comes from Modifier.testTag), act with performClick, and check it with assertIsDisplayed, assertExists or assertTextEquals.

solid answer

~30 s

I declare `@get:Rule val composeTestRule = createComposeRule()` imported from `androidx.compose.ui.test.junit4.v2`, then call `setContent` exactly once with the screen fed fake data. Finders such as `onNodeWithText("Alto")` or `onNodeWithTag("rehearsal-list")` search the merged semantics tree and return a `SemanticsNodeInteraction`; the tag comes from `Modifier.testTag`. I act with `performClick()` or `performTextInput()` and check with `assertIsDisplayed()`, `assertExists()`, `assertDoesNotExist()` or `assertTextEquals()`. Every action and assertion first synchronizes with Compose, so no sleeps are needed. A single-node finder that matches no node or several nodes fails with an `AssertionError`, so for repeated rows I use `onAllNodesWithTag(...)` with `assertCountEquals`.

code

kotlin · 23 lines
kotlin
import androidx.compose.ui.test.assertIsDisplayed
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 org.junit.Rule
import org.junit.Test

class RehearsalFilterTest {
    @get:Rule val composeTestRule = createComposeRule()

    @Test
    fun filteringByAltoHidesBassRehearsals() {
        composeTestRule.setContent {
            RehearsalScreen(rehearsals = fakeRehearsals)
        }

        composeTestRule.onNodeWithText("Alto").performClick()

        composeTestRule.onNodeWithTag("row-alto-tue").assertIsDisplayed()
        composeTestRule.onNodeWithTag("row-bass-wed").assertDoesNotExist()
    }
}

go deeper

for a junior

Recall the shape: v2 createComposeRule, setContent once, a finder by text or tag, a perform call, an assert call. Know where a test tag comes from.

for a middle

Explain that finders search the merged semantics tree, that single-node finders demand exactly one match, and that each call synchronizes with Compose first.

for a senior

Show judgement on locators: prefer user-visible text, add tags where text is unstable, and keep tests on fake state so they are fast and deterministic.

for a principal

Weigh how a team keeps tags meaningful as screens change and how much screen behaviour it covers with these tests versus slower end-to-end runs.

## What a Compose UI test looks at A Compose screen has no `View` per element, so a Compose UI test cannot look things up by view id. Instead it reads the **semantics tree**: a parallel tree Compose builds next to the UI, where each node carries properties such as its text, content description, role, test tag and the actions it supports (click, scroll, set text). The same tree feeds accessibility services, which is why a test that finds a button by its visible label is close to what a screen-reader user experiences. The testing library (`androidx.compose.ui:ui-test-junit4`) gives you three kinds of calls on that tree: - **Finders** select one node or several nodes. - **Actions** inject user input into a selected node. - **Assertions** check a selected node's properties or presence. ## Setting up the rule 1. Add `androidTestImplementation("androidx.compose.ui:ui-test-junit4:...")` and, for `createComposeRule()`, `debugImplementation("androidx.compose.ui:ui-test-manifest:...")`, which registers the empty `ComponentActivity` the rule launches. 2. Declare the rule with the **v2** factory: `@get:Rule val composeTestRule = createComposeRule()` imported from `androidx.compose.ui.test.junit4.v2`. The v2 package arrived in Compose 1.11; the older `androidx.compose.ui.test.junit4.createComposeRule` is deprecated in 1.12. 3. Call `composeTestRule.setContent { ... }` **exactly once** per test with the composable under test, ideally fed fake state. A second call throws `IllegalStateException`. Use `createAndroidComposeRule<YourActivity>()` when the test needs a real Activity or its resources (`composeTestRule.activity.getString(...)`). If that Activity calls `setContent` itself, do not call `setContent` on the rule as well; the rule rejects it with an `IllegalStateException`. ## Finders | Finder | Matches | Note | |---|---|---| | `onNodeWithText("Alto")` | displayed or editable text equal to the string | `substring` and `ignoreCase` default to `false` | | `onNodeWithTag("rehearsal-list")` | the `TestTag` semantics property | set by `Modifier.testTag("rehearsal-list")` | | `onNodeWithContentDescription("Filter")` | content description | typical for icons | | `onNode(hasText("Alto") and hasClickAction())` | any `SemanticsMatcher` combination | `and`, `or` combine matchers | | `onAllNodesWithTag("rehearsal-row")` | every matching node | returns a collection | Every finder takes `useUnmergedTree`, defaulting to `false`, so by default it searches the **merged** tree, where a button and its label appear as one node. A single-node finder is lazy: the lookup happens when you act or assert. If it then finds no node, or more than one, it throws an `AssertionError` whose message says it expected exactly one node and lists what it found. For lists, use the collection finders with `assertCountEquals(3)`, `onFirst()`, `get(index)` or `filter(...)`. ## Actions and assertions - `performClick()` injects a touch click at the node's centre. - `performTextInput("Tenor")` focuses an editable node and inserts text; `performTextReplacement` replaces it. - `assertExists()` passes when the node is anywhere in the semantics tree, even off screen. - `assertIsDisplayed()` additionally requires that the node is placed and at least part of it is visible after clipping. - `assertDoesNotExist()` passes when no node matches. - `assertTextEquals("Alto", "Tue 19:00")` requires the node's text values to be exactly that list. - `assert(hasClickAction())` takes any matcher. ## Synchronization you get for free Before each action or assertion, the rule waits until Compose is idle: no pending recompositions, animations it drives or layout passes, and every registered idling resource idle. It advances a **virtual test clock** to get there, so tests run fast and do not need `Thread.sleep` for Compose's own work. Work that Compose cannot see, such as a repository loading on a background thread, is not covered and needs `waitUntil`. The function form, `runComposeUiTest { ... }` from `androidx.compose.ui.test.v2`, offers the same finders, actions and synchronization on its receiver instead of on a rule object; in 1.12 it is marked `@ExperimentalTestApi`, so a test opts in to use it. ## Where the test runs and what it should feed - The same test runs as an instrumented test from `androidTest` on a device or emulator, or on the JVM with Robolectric from the `test` source set. - Feed the composable fixed, fake state, such as three rehearsals on fixed dates, rather than a live backend, so assertions are deterministic and the test checks the UI rather than the network. - Keep one behaviour per test: one filter click and the assertions that prove it. - When a finder fails, `composeTestRule.onRoot().printToLog("RehearsalTree")` prints the semantics tree to logcat, showing what the test could actually see. ## Common mistakes - Reaching for Espresso's `onView` to find a composable; View matchers do not see semantics nodes. - Treating `assertExists()` as proof that the user can see the node. - Adding test tags everywhere instead of finding nodes by the text a user sees; tags are best for nodes with no stable text. - Asserting on a single-node finder when several rows share a tag.

  • When would you use createAndroidComposeRule instead of createComposeRule?
    When the test needs a specific Activity: to read resources through `composeTestRule.activity`, or to launch the real entry Activity. `createAndroidComposeRule<ComponentActivity>()` plus `setContent` is the usual way to get resources while still choosing the content. If the launched Activity calls `setContent` itself, test what it shows and do not call `setContent` on the rule, which throws `IllegalStateException`.
  • Several rehearsal rows share the tag "rehearsal-row"; how do you assert on the Alto row only?
    Narrow the matcher instead of the finder count: `onNode(hasTestTag("rehearsal-row") and hasText("Alto"))`, or take the collection with `onAllNodesWithTag("rehearsal-row")` and use `filterToOne(hasText("Alto"))`, `onFirst()` or `get(index)`. `assertCountEquals(n)` checks how many rows there are.

  • Thread.sleep after a click is needed before the UI updates
  • onNodeWithText clicks the first match when two nodes share the text
  • Compose nodes are found with Espresso onView and view ids
  • assertExists proves the user can see the node
  • setContent can be called again mid-test to swap screens

Assumes Compose UI testing 1.12; createComposeRule comes from the v2 package added in 1.11, and the v1 factory is deprecated.