Discovering Espresso for Android: matching and asserting view with text.

After more than a month of using great test tool from Google - Espresso for Android, we'd like to share with you some of our experience. We assume that you've already added espresso jar into your project, spent some time playing with Espresso samples and have basic understanding how this tool works.

It will be explained how to match particular view with text or assert that it contains (or not) specified Strings. Before we start, you have to take a look at Hamcrest matchers - Hamcrest tutorial and API Reference Documentation, which are used together with Espresso's ViewAssertions and ViewMatchers and included into Espresso standalone library. Pay more attention to java.lang.String matchers.

So, here we go. For simplicity following String XXYYZZ will be used as a expected text pattern.

Espresso ViewMatchers class implements two String matcher methods withText() and withContentDescription() which will match a view which text is equal to specified expectedText or specified expectedContentDescriptionText parameter passed into it.

onView(withText("XXYYZZ"))
        .perform(click());
onView(withContentDescription("XXYYZZ"))
        .perform(click());

Using Hamcrest String matchers we can create more flexible matcher combinations:

  • matching a view which text starts with XXYY pattern:

    onView(withText(startsWith("XXYY")))
        .perform(click());
  • matching a view which text ends with YYZZ pattern:

    onView(withText(endsWith("YYZZ")))
        .perform(click());
  • assert that text of a particular view with specified R.id has content description which contains YYZZ string anywhere:

    onView(withId(R.id.viewId))
        .check(matches(withContentDescription(containsString("YYZZ"))));
  • matching a view which text is equal to the specified string, ignoring case:

    onView(withText(equalToIgnoringCase("xxYY")))
        .perform(click());
  • matching a view which text is equal to the specified text when whitespace differences are (mostly) ignored:

    onView(withText(equalToIgnoringWhiteSpace("XX YY ZZ")))
        .perform(click());
  • assert that text of a particular view with specified R.id does not contain YYZZ string:

    onView(withId(R.id.viewId))
        .check(matches(withText(not(containsString("YYZZ")))));

Adding allOf() or anyOf() Hamcrest Core matchers gives us even more power:

  • assert that text of a particular view with specified R.id doesn't start with ZZ string and contains YYZZ string anywhere:

    onView(withId(R.id.viewId))
        .check(matches(allOf(
            withText(not(startsWith("ZZ"))), 
            withText(containsString("YYZZ")))));
  • assert that text of a particular view with specified R.id ends with ZZ string or contains YYZZ string anywhere:

    onView(withId(R.id.viewId))
        .check(matches(anyOf(
            withText(endsWith("ZZ")), 
            withText(containsString("YYZZ")))));