skip to content

After moving a Compose test from the deprecated createComposeRule to the v2 one, why does an assertion right after launching work fail, and how do you fix it?

level: seniorimportance: should knowfreq 38%

answer

  1. which dispatcher runs the composition
  2. eager versus queued launches
  3. v2 arrived in Compose 1.11
  4. waitForIdle or runOnIdle drains the queue
  5. mainClock.scheduler.runCurrent() keeps time still

basics

~20 s

The v2 rule runs composition coroutines on a StandardTestDispatcher, so a launch is queued instead of running eagerly as under the old UnconfinedTestDispatcher. Drain the queue first: waitForIdle or runOnIdle, or mainClock.scheduler.runCurrent() when autoAdvance is off.

solid answer

~40 s

The v1 factories run composition on an `UnconfinedTestDispatcher`, so a coroutine launched from a composition scope ran immediately and often finished before the next test line. The v2 `createComposeRule`, `createAndroidComposeRule` and `runComposeUiTest`, added in Compose 1.11, use a `StandardTestDispatcher`: the launch is queued on the test scheduler until something runs it. An assertion on plain state right after `listState.refresh()` therefore sees the old value. The fix is to synchronize: assert through finders, which wait for idle; call `waitForIdle()` first; or wrap the check in `runOnIdle { }`. With `mainClock.autoAdvance = false`, `mainClock.scheduler.runCurrent()` runs what is due without moving the clock. The failure was a real ordering assumption the old dispatcher hid.

code

kotlin · 27 lines
kotlin
import androidx.compose.ui.test.junit4.v2.createComposeRule
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test

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

    @Test
    fun refreshLoadsRehearsals() {
        lateinit var listState: RehearsalListState
        composeTestRule.setContent {
            // The app's state holder launches loads in rememberCoroutineScope()
            listState = rememberRehearsalListState(FakeRehearsalRepository(count = 3))
            RehearsalList(listState)
        }

        listState.refresh()

        // Passed on the v1 rule, fails on v2: the launch is still queued
        // assertEquals(3, listState.rehearsals.size)

        composeTestRule.runOnIdle {
            assertEquals(3, listState.rehearsals.size)
        }
    }
}

go deeper

for a junior

Recall that the v2 test rules live in packages ending in v2 and that coroutines launched from a composition scope may not have run yet when the next line executes.

for a middle

Explain eager UnconfinedTestDispatcher versus queued StandardTestDispatcher in the composition, and which Compose test calls drain the queue: finders, waitForIdle, runOnIdle and runCurrent.

for a senior

Diagnose a suite that breaks after the v2 migration: tell real ordering assumptions from app bugs and fix them with waitForIdle, runOnIdle or runCurrent rather than restoring eager dispatch.

for a principal

Plan the migration for a large suite: move imports in one sweep, budget for fixing hidden ordering assumptions, and forbid new tests on the deprecated rules.

## What changed between the two rules A Compose test runs composition, `LaunchedEffect` blocks and `rememberCoroutineScope` launches on a coroutine dispatcher that the test environment controls. Which dispatcher that is depends on the entry point: | Entry point | Package | Default composition dispatcher | |---|---|---| | `createComposeRule`, `createAndroidComposeRule`, `runComposeUiTest` (v1, deprecated) | `androidx.compose.ui.test.junit4`, `androidx.compose.ui.test` | `UnconfinedTestDispatcher` | | `createComposeRule`, `createAndroidComposeRule`, `runComposeUiTest` (v2, since 1.11) | `androidx.compose.ui.test.junit4.v2`, `androidx.compose.ui.test.v2` | `StandardTestDispatcher` | The two `kotlinx-coroutines-test` dispatchers differ in one way that matters here: - **`UnconfinedTestDispatcher`** starts a launched coroutine eagerly, on the calling thread, up to its first real suspension. - **`StandardTestDispatcher`** queues the coroutine on the shared `TestCoroutineScheduler`; it runs only when the scheduler runs its due tasks. The Android docs call that immediate execution unlike production behaviour and warn that it could mask real timing issues and race conditions. The deprecation message on the v1 factories says the same: the v2 APIs queue tasks rather than executing them immediately, and tests relying on immediate execution may need explicit synchronization. ## The failure pattern The typical breakage after a find-and-replace of imports: 1. The test obtains a state holder from the composition, for example a `RehearsalListState` the screen creates with `rememberCoroutineScope()`. 2. The test calls `listState.refresh()`, which launches a load in that scope. 3. The very next line reads `listState.rehearsals` with a plain JUnit assertion. Under v1 the launch ran to completion inside `refresh()`, because the fake repository never really suspends. Under v2 it sits in the queue, the list is still empty, and the assertion fails. Nothing is wrong with the app; the test assumed an ordering that production does not have. Tests that check results through Compose finders mostly keep working, because every action and assertion first synchronizes, and on the v2 rules that synchronization runs the scheduler's due tasks before deciding the UI is idle. ## Fixes, from most to least common 1. **Assert through the UI.** `onNodeWithTag("rehearsal-row")...` synchronizes first. 2. **`composeTestRule.waitForIdle()`** before a plain assertion: it advances the clock until Compose is idle, running queued coroutines on the way. 3. **`composeTestRule.runOnIdle { ... }`**: waits for idle, then runs the block on the UI thread, which is the recommended place to read shared state. 4. **`composeTestRule.mainClock.scheduler.runCurrent()`** when `mainClock.autoAdvance = false`: runs tasks due at the current virtual time without moving the clock, so a test can see an intermediate state that an auto-advancing `waitForIdle()` would skip. An escape hatch exists: `effectContext` accepts a `TestDispatcher`, so passing an `UnconfinedTestDispatcher` restores eager launches on a v2 rule. Use it only as a temporary bridge; it reintroduces the masking the change removed. ## runTest and the second clock A related trap: wrapping a rule-based test body in `runTest { advanceTimeBy(1_000) }` creates a second scheduler. Advancing it does not advance Compose's clock, so a `LaunchedEffect` with `delay(1_000)` never finishes. The docs recommend `runComposeUiTest`, which runs its suspending block in its own `runTest` scope with a clock synchronized to Compose. In 1.12 `runComposeUiTest` and its `ComposeUiTest` receiver are marked `@ExperimentalTestApi`, so the test opts in. The alternative is sharing `composeTestRule.mainClock.scheduler` with `runTest`. ## Telling a test bug from an app bug After migration, read each new failure before touching it: - If the assertion reads plain state right after an action and passes once `waitForIdle()` precedes it, the test assumed eager execution; fix the test. - If the UI itself shows the wrong thing even after the test synchronizes, for example the rehearsal list renders stale rows after `refresh()` and idle, the queued order exposed a real race in the app; fix the app and keep the test. - If a test only passes with an `UnconfinedTestDispatcher` passed back in, it depends on an ordering production does not guarantee; rewrite it around observable UI state. That triage is the value of the change: v1 ran launches in an order unlike production, so some of these app bugs were invisible before. ## Migrating a suite - Change imports to the `v2` packages; the call sites stay the same. - Run the suite and fix failures by synchronizing, not by restoring the old dispatcher. - Watch for tests that subclass or construct `AndroidComposeUiTestEnvironment` directly: its default composition dispatcher also switched to `StandardTestDispatcher`. - Treat each fix as a finding: a test that needed eager execution was checking an order the app did not guarantee.

  • Why not pass UnconfinedTestDispatcher as effectContext to make the old tests pass again?
    It works, because a `TestDispatcher` in `effectContext` is used for composition, but it brings back the eager execution the docs describe as unlike production, so tests can again pass while the app has an ordering bug. Use it only as a short bridge during migration and fix each test by synchronizing.
  • When do you prefer mainClock.scheduler.runCurrent() to waitForIdle()?
    When the test wants an intermediate state. `runCurrent()` runs only tasks due at the current virtual time and keeps the clock where it is, so the test can see, say, a loading indicator before a delayed step. With `autoAdvance` on, `waitForIdle()` advances the clock until Compose settles and can skip past that moment; with the clock held, `runCurrent()` is the direct way to run queued launches.

  • The v2 rule runs composition on UnconfinedTestDispatcher like v1
  • A failure after migrating to v2 means the screen has a bug
  • Wrapping the test in runTest advances Compose's clock too
  • Switching to v2 means rewriting every finder and assertion
  • runCurrent advances the virtual clock to the next delayed task

Assumes Compose UI testing 1.12; the v2 rules and runComposeUiTest arrived in 1.11 with StandardTestDispatcher, while the deprecated v1 entry points keep UnconfinedTestDispatcher.