Espresso
01 / 02

onView, Matchers, Actions & Assertions

onView, Matchers, Actions & Assertions

The Core Pattern

@Test
fun clickingSubmit_showsSuccessMessage() {
    onView(withId(R.id.email_input))
        .perform(typeText("user@example.com"), closeSoftKeyboard())

    onView(withId(R.id.submit_button))
        .perform(click())

    onView(withId(R.id.status_text))
        .check(matches(allOf(isDisplayed(), withText("Success"))))
}

onView(matcher).perform(action).check(assertion) is Espresso's signature pattern: find a view, act on it, assert the result. withId()/withText()/withContentDescription() are ViewMatchers; click()/typeText()/scrollTo() are ViewActions; matches(isDisplayed()) etc. are ViewAssertions.

Resolving Ambiguous Matches

// AmbiguousViewMatcherException if two "Submit" texts exist on screen
onView(allOf(withText("Submit"), withId(R.id.submit_button)))
    .perform(click())

Automatic Synchronization

Espresso waits for the main thread's message queue to go idle before proceeding — no pending UI updates or animations — which is why most tests need no manual Thread.sleep(). This significantly reduces flakiness compared to tools without this synchronization.

IdlingResource for Custom Async Work

For background work Espresso can't automatically detect (like an in-flight network call via Retrofit/OkHttp), register an IdlingResource so Espresso waits for it before continuing to the next step.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free