skip to content

Espresso

Android's instrumented View test framework: onView with matchers, actions and assertions, synced to the main thread. Asked because idle sync makes UI tests deterministic; IdlingResource follows.

on this pageshow

explore

questions

6

In Espresso, what do onView, perform and check each do, and what happens when the matcher finds no view or several views?

level: juniorimportance: must knowfreq 72%

answer

  1. find, act, then verify
  2. a Hamcrest matcher picks the view
  3. ViewActions versus ViewAssertions
  4. exactly one match required
  5. two different exceptions on failure

basics

~10 s

onView takes a ViewMatcher that must match exactly one view, perform runs ViewActions such as click() on it, and check applies a ViewAssertion such as matches(isDisplayed()). No match throws NoMatchingViewException; several matches throw AmbiguousViewMatcherException.

solid answer

~40 s

An Espresso interaction has three parts. `onView(withId(R.id.sign_in))` takes a Hamcrest `Matcher<View>` from `ViewMatchers` and returns a `ViewInteraction`; it does not touch the app yet. `perform(typeText("[email protected]"), closeSoftKeyboard())` runs one or more `ViewActions` in order, and `check(matches(withText("Welcome, Ana")))` applies a `ViewAssertion`. Before every action and assertion Espresso syncs with the main thread, so the test needs no sleeps. The matcher must match exactly one view in the current hierarchy: none throws `NoMatchingViewException`, several throw `AmbiguousViewMatcherException`, and the message prints the view hierarchy, marking each ambiguous hit with `MATCHES`. You narrow a match with `allOf(withId(...), withText(...))`, and you assert absence with `doesNotExist()`, because `matches(...)` first requires the view to exist.

code

kotlin · 16 lines
kotlin
@RunWith(AndroidJUnit4::class)
class LoginScreenTest {

    @get:Rule
    val activityRule = ActivityScenarioRule(LoginActivity::class.java)

    @Test
    fun signInShowsWelcome() {
        onView(withId(R.id.email)).perform(typeText("[email protected]"), closeSoftKeyboard())
        onView(withId(R.id.password)).perform(typeText("correct-horse"), closeSoftKeyboard())
        onView(withId(R.id.sign_in)).perform(click())

        onView(withText("Welcome, Ana")).check(matches(isDisplayed()))
        onView(withId(R.id.error_banner)).check(doesNotExist())
    }
}

go deeper

for a junior

Recall the three steps and their classes: onView with a ViewMatcher, perform with ViewActions, check with a ViewAssertion. Know the two exceptions for zero and several matches.

for a middle

Explain why onView is lazy and when the lookup happens, why click() needs the view 90 percent visible, and why doesNotExist() differs from matches(not(isDisplayed())).

for a senior

Show how you read the hierarchy dump in NoMatchingViewException and AmbiguousViewMatcherException to fix a matcher, and why you keep assertions out of onView so failures report the real cause.

for a principal

Talk about matcher hygiene as a team rule: stable ids and content descriptions in layouts, least-descriptive matchers, and treating an unmatchable view as an accessibility defect rather than a test problem.

## What an Espresso test is **Espresso** is Android's instrumented UI test framework for the View system. Instrumented means the test runs on a device or emulator, in the same process as the app under test, driven by `AndroidJUnitRunner`. The API is deliberately small: you never get a `View` or an `Activity` object to poke at from the test thread. Instead you describe **which view** you want, **what to do** to it and **what must be true** about it, and Espresso does the work on the main thread at a moment when the app is at rest. ## The three pieces of one interaction | Piece | Class you pass | Typical members | What it returns | |---|---|---|---| | Find | `Matcher<View>` from `ViewMatchers` | `withId`, `withText`, `withContentDescription`, `isDisplayed`, `hasDescendant` | `onView(...)` returns a `ViewInteraction` | | Act | `ViewAction` from `ViewActions` | `click`, `typeText`, `replaceText`, `closeSoftKeyboard`, `scrollTo`, `pressBack` | `perform(...)` returns the same `ViewInteraction` | | Verify | `ViewAssertion` from `ViewAssertions` | `matches(...)`, `doesNotExist()` | `check(...)` returns the same `ViewInteraction` | Because `perform` and `check` both return the interaction, you can chain them: `onView(withId(R.id.sign_in)).perform(click()).check(matches(isDisplayed()))`. `perform` also takes several actions at once and runs them in order, which is how you type into a field and close the keyboard in one line. A few points about how these pieces behave: - **`onView` is lazy.** It only builds the interaction. The view is looked up when `perform` or `check` runs, after Espresso has waited for the main thread to go idle. - **Actions have constraints.** `click()` requires the view to be at least 90% displayed. `scrollTo()` works on a view inside a scrolling container such as a `ScrollView` or `NestedScrollView`, and does nothing if the view is already shown, so `perform(scrollTo(), click())` is safe on small and large screens alike. - **Every action is logged** to logcat (for example `Performing 'single click' action on view with text: ...`), which helps when reading a CI failure. ## The view matcher must match exactly one view The rule interviewers check first is that the matcher passed to `onView` must match **one and only one** view in the current hierarchy. 1. **No match** throws `NoMatchingViewException`. The message contains the whole view hierarchy so you can see what was on screen. If the hierarchy holds an `AdapterView` such as a `ListView`, the message also warns you, because the row you wanted may not have been created yet and `onData` is the entry point for it. 2. **Several matches** throw `AmbiguousViewMatcherException`. The message prints the hierarchy and marks each matching view with `MATCHES`, which typically happens when an `R.id` is reused, for example in an included layout or a list row. 3. **One match** lets the action or assertion run. You fix an ambiguous match by combining matchers: `onView(allOf(withId(R.id.title), withText("Sign in")))`, or `isDescendantOfA(...)` to scope the search to one container. The documentation's advice is to use the **least descriptive matcher** that still finds one view; over-specifying makes the framework do more work and makes the test brittle. If a view can only be told apart by its position in the tree, Android's guidance treats that as an accessibility gap: the view probably needs visible text or a content description. ## Asserting presence, visibility and absence `matches(...)` is the assertion you use most. It asserts that the view **exists** and that it satisfies the matcher you pass. That has a consequence people miss: - `check(matches(isDisplayed()))` passes when the view is at least partly on screen; `isCompletelyDisplayed()` demands the whole view. - `check(matches(not(isDisplayed())))` passes for a view that is in the hierarchy but hidden or off screen. It **fails** with `NoMatchingViewException` if the view is not in the hierarchy at all. - `check(doesNotExist())` is the assertion for "this view is gone", such as an error banner that was removed. - `withEffectiveVisibility(Visibility.GONE)` checks the visibility flag itself, including the parents'. Keep what you are verifying inside `check`. Writing `onView(allOf(withId(R.id.greeting), withText("Hello"))).check(matches(isDisplayed()))` turns a wrong text into a confusing "no such view" error instead of an assertion that shows the text the view really has. ## Launching the screen under test The test needs an activity on screen first. `ActivityScenarioRule` (from the AndroidX Test JUnit extensions) launches the activity before each test and closes it afterwards; `ActivityScenario.launch(...)` does the same by hand. `ActivityTestRule` is the older rule, deprecated in AndroidX Test Rules 1.3.0 in favour of these two. ## Common mistakes - Adding `Thread.sleep` between steps: Espresso already waits for the main thread, and sleeps hide the real synchronisation problem. - Expecting Espresso to pick the first of several matches: it refuses and throws. - Using `matches(not(isDisplayed()))` to prove a view was removed. - Holding on to a `View` reference from the test and touching it off the main thread, which is exactly the flakiness the API is designed to prevent.

  • Why does Espresso's documentation warn against putting withText inside onView when what you mean is to assert the text?
    Because the failure then reports the wrong thing. With `onView(allOf(withId(R.id.greeting), withText("Hello"))).check(matches(isDisplayed()))`, a wrong text gives `NoMatchingViewException`, as if the view were missing. Locate the view with the least descriptive matcher that finds exactly one, then put the claim in `check(matches(withText("Hello")))`, so a failure shows the text the view actually has.
  • Your click() fails with a PerformException saying the view must be at least 90 percent displayed; what do you do?
    `click()` refuses a view that is less than 90% on screen. If the view sits inside a `ScrollView` or `NestedScrollView`, run `perform(scrollTo(), click())`; `scrollTo()` does nothing when the view is already visible, so the same test works on small and large screens. If something overlaps it, such as the soft keyboard, close it first with `closeSoftKeyboard()`.
  • How do you tell two buttons apart when they share one id inside included layouts?
    Combine matchers so exactly one view matches: `allOf(withId(R.id.save), isDescendantOfA(withId(R.id.billing_section)))`, or add `withText` or `withContentDescription`. Read the `AmbiguousViewMatcherException` message first; it prints the hierarchy and marks every matching view with `MATCHES`, which shows which attribute differs between them.

  • If several views match, Espresso simply acts on the first one
  • matches(not(isDisplayed())) proves a view was removed from the hierarchy
  • Add Thread.sleep after a click so the next screen has time to draw
  • check() is where you call actions such as click() or typeText()
  • Espresso tests run on the local JVM without a device or emulator

Assumes Espresso 3.7.0 with androidx.test core 1.7.0; ActivityTestRule is deprecated since AndroidX Test Rules 1.3.0 in favour of ActivityScenarioRule.

open as a page

Before each Espresso action or assertion, what does Espresso wait for on its own, what work can it not see, and why turn animations off?

level: middleimportance: must knowfreq 58%

basics

~20 s

Espresso waits until the main message queue has nothing due, no AsyncTask runs and all registered idling resources are idle. Your own threads, executors and coroutine dispatchers are invisible to it; animations go off because they cause flakiness.

open as a page

An Espresso login test passes locally but flakes on CI while the sign-in network call completes; how do you fix it with an IdlingResource?

level: seniorimportance: must knowfreq 50%

basics

~20 s

The sign-in call runs off the main thread, so Espresso asserts before the response arrives. Wrap the call in a CountingIdlingResource (increment before, decrement in finally), register it with IdlingRegistry in @Before and unregister it in @After.

open as a page

In Espresso, when do you use onData instead of onView, and how do you click an off-screen RecyclerView row with RecyclerViewActions?

level: middleimportance: should knowfreq 45%

basics

~20 s

Use onData for AdapterView lists such as ListView, GridView and Spinner: it matches the adapter's data object and loads that row before acting. RecyclerView is not an AdapterView, so you call onView on the RecyclerView and perform a RecyclerViewActions action from espresso-contrib.

open as a page

As Android lead, how large a share of UI tests should be Espresso tests, and do you standardise on idling resources or injected idling-aware dispatchers for synchronisation?

level: principalimportance: should knowfreq 22%

basics

~20 s

Keep Espresso for flows that need a real View hierarchy on a device and pin everything else lower. For synchronisation, pick one team standard: injected idling-aware executors cover most background work automatically, CountingIdlingResource covers the rest explicitly, and sleeps are banned.

open as a page

With Espresso-Intents, how do intended and intending differ, and how do you test a sign-in screen that picks a phone number from the contacts app?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

intended(matcher) verifies, like Mockito's verify, that the app sent exactly one matching activity intent; intending(matcher).respondWith(result) stubs it, so the external activity never opens and the app receives a canned ActivityResult. IntentsRule initialises and releases the recording around each test.

open as a page