Exit course
Chapter 3 of 10 Intermediate 7 min read 2 quick checks Updated

ViewMatchers, ViewActions and ViewAssertions

On this page
  1. ViewMatchers: say which view you mean
  2. The two errors you will see most
  3. ViewActions: do what the user does
  4. ViewAssertions: check the result
  5. The login tests

Every line of an Espresso test is built from three kinds of objects. A ViewMatcher describes which view you mean. A ViewAction does something to it. A ViewAssertion checks something about it. Once you know the handful that cover most tests, and the two errors Espresso throws when a matcher is wrong, you can test almost any screen built with Android views.

onView(withId(R.id.login))     // ViewMatcher: which view
    .perform(click())          // ViewAction: what to do
onView(withId(R.id.error))
    .check(matches(isDisplayed()))  // ViewAssertion: what must be true

All three live in espresso-core. Their packages are androidx.test.espresso.matcher.ViewMatchers, androidx.test.espresso.action.ViewActions and androidx.test.espresso.assertion.ViewAssertions; Android Studio imports them for you.

ViewMatchers: say which view you mean#

onView() takes a Hamcrest matcher and searches the current window's view hierarchy for exactly one view that matches it. The matchers you will use most:

Matcher Matches Use it when
withId(R.id.login) The view with that id The view has an id. This is the default choice.
withText("Log in") A TextView (or Button, EditText) with that text There is no id, or the text is what you are testing
withText(R.string.login_failed) Text from a string resource You check copy that may change or be translated
withHint("Password") An EditText with that hint Empty fields without ids
withContentDescription("Close") A view with that accessibility label Icon buttons
isDisplayed() A view that is at least partly on screen Narrowing a matcher that would otherwise match hidden views

Combine them with Hamcrest's allOf when one matcher is not specific enough:

onView(allOf(withId(R.id.add), hasSibling(withText("Product 3"))))

Prefer ids. Text changes when someone rewrites the copy or the device runs in another language; ids are part of the code and the compiler checks them. When you do match on copy, withText(R.string.login_failed) follows the string resource wherever it goes, including translations.

The two errors you will see most#

A matcher must match exactly one view in the hierarchy. When it does not, Espresso throws one of two exceptions, and the message tells you which mistake you made. Both of these came from real runs against the sample app's product list:

androidx.test.espresso.AmbiguousViewMatcherException:
'an instance of android.widget.TextView and view.getText() with or without
transformation to match: is "Add"' matches 10 views in the hierarchy

Every row in the list has an "Add" button, so withText("Add") is ambiguous. (Ten, because only ten rows exist as views at that moment: a RecyclerView creates views for the visible rows only.) The fix is a more specific matcher, or, for lists, the RecyclerViewActions in the next chapter.

androidx.test.espresso.NoMatchingViewException: No views in hierarchy found
matching: an instance of android.widget.TextView and view.getText() with or
without transformation to match: is "Product 42"

"Product 42" exists in the adapter's data, but its row is far below the screen, so no view for it has been created yet. Espresso only sees views that exist. Under the message, both exceptions print the whole view hierarchy, which is the fastest way to see what Espresso actually found.

onView(withText("Delete")).perform(click()) fails with AmbiguousViewMatcherException on a screen with a toolbar Delete action and a Delete button in a dialog. What do you change?

The error means more than one view matched; timing has nothing to do with it. A more specific matcher picks exactly one view. Espresso deliberately offers no "first match" fallback, because a test that clicks whichever view comes first breaks silently when the layout changes.

ViewActions: do what the user does#

perform() takes one or more actions and runs them in order on the matched view:

Action What it does
click() Taps the centre of the view
typeText("alice") Focuses the field and types through the keyboard, character by character
replaceText("alice") Sets the text directly, without the keyboard
clearText() Empties a text field
closeSoftKeyboard() Hides the on-screen keyboard
pressImeActionButton() Presses the keyboard's action key (Done, Search, Next)
scrollTo() Scrolls a ScrollView until the view is visible
swipeLeft(), swipeUp(), ... Swipes on the view

typeText behaves most like a user and triggers text watchers and input filters on each character. replaceText is faster and does not depend on the keyboard, which makes it the better choice when you only need the field filled in. Whichever you use, close the keyboard before tapping something below the fields: on a small screen the keyboard covers the Log in button, and Espresso refuses to click a view that is not displayed enough to receive the tap.

scrollTo() is meant for views inside a ScrollView (or NestedScrollView, HorizontalScrollView). It cannot bring an off-screen RecyclerView row into view: onView(withText("Product 42")).perform(scrollTo()) fails with the same NoMatchingViewException as above, because the row's view does not exist yet for onView to find. Lists get their own actions in the next chapter.

ViewAssertions: check the result#

check() takes an assertion. Nearly every assertion you write is matches(...) with a view matcher inside:

onView(withId(R.id.error)).check(matches(withText(R.string.login_failed)))
onView(withId(R.id.progress)).check(matches(not(isDisplayed())))
onView(withId(R.id.welcome)).check(doesNotExist())

The difference between the last two matters. matches(not(isDisplayed())) needs the view to exist and be hidden; it throws NoMatchingViewException if the view is not in the hierarchy at all. doesNotExist() passes only when no view matches. Use the first for a spinner that is hidden, the second for a screen you have left.

check() returns the same ViewInteraction, so assertions chain:

onView(withId(R.id.error))
    .check(matches(isDisplayed()))
    .check(matches(withText(R.string.login_failed)))

The login tests#

Put together, the first real tests for the login screen in LoginTest.kt:

@RunWith(AndroidJUnit4::class)
class LoginTest {

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

    @Test
    fun validLoginOpensProducts() {
        onView(withId(R.id.username)).perform(typeText("alice"))
        onView(withId(R.id.password)).perform(typeText("secret"), closeSoftKeyboard())
        onView(withId(R.id.login)).perform(click())

        onView(withId(R.id.welcome)).check(matches(withText("Welcome, alice")))
    }

    @Test
    fun wrongPasswordShowsError() {
        onView(withId(R.id.username)).perform(typeText("alice"))
        onView(withId(R.id.password)).perform(typeText("nope"), closeSoftKeyboard())
        onView(withId(R.id.login)).perform(click())

        onView(withId(R.id.error))
            .check(matches(isDisplayed()))
            .check(matches(withText(R.string.login_failed)))
    }
}

R.id.welcome lives on the next screen, ProductsActivity. Espresso does not care which activity a view belongs to: onView searches whatever window is in front.

Run them, and both fail:

Error in wrongPasswordShowsError(com.example.shop.LoginTest):
Expected: an instance of android.widget.TextView and view.getText() equals
string from resource id: <2131492900> [login_failed] value: Wrong username or password
     Got: view.getText() was ""

Error in validLoginOpensProducts(com.example.shop.LoginTest):
androidx.test.espresso.NoMatchingViewException: No views in hierarchy found
matching: view.getId() is <2131230910/com.example.shop:id/welcome>

The tests are right; the app checks the password on a background thread that takes 1.5 seconds, and Espresso checked the result immediately. This is the one situation where Espresso's automatic waiting needs help, and chapter 4 fixes it properly, without a sleep. Keep both tests as they are until then.

After logging out, you want to assert that the welcome text is gone because the products screen has closed. Which check is right?

Once the activity is finished, its views are no longer in the hierarchy. matches(not(isDisplayed())) would throw NoMatchingViewException because it needs a view to inspect; doesNotExist() is the assertion for "no such view".