android-espresso How to Create Custom Matchers?

Example of Custom matcher for testing TextView error message

  1. Create a class name ErrorMatcher inside your test package with below code:
public class ErrorMatcher {

    public static Matcher<View> withError(final String expectedErrorText) {
        return new BoundedMatcher<View, TextView>(TextView.class) {    
            public void describeTo(final Description description) {
                description.appendText("error text: ");
            public boolean matchesSafely(final TextView textView) {
                return expectedErrorText.equals(textView.getError().toString());

Matching logic is to find the TextView element, which error message text is equal to expected error text value, going through the subset of TextView fields present in the layout hierarchy. describeTo method is used for debug output.

  1. Then you can use your custom matcher in the test case as shown below:
public void verifiesSignInErrorIsShown() {
    onView(ErrorMatcher.withError("Your error text")).check(matches(isDisplayed()));