android-espresso How to Create Custom Matchers? Example of Custom matcher for testing TextView error message

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


  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()));

Got any android-espresso Question?