Saturday, November 3, 2018

how to create custome Matcher in Espresso android studio

Create a class name  ErrorMatcher in androidTest folder.


public class ErrorMatcher {



@NonNull

public static Matcher withError(final Matcher stringMatcher) {

return new BoundedMatcher(TextView.class) {


@Override

public void describeTo(final Description description) {
description.appendText("error text: ");
stringMatcher.describeTo(description);
}


@Override

public boolean matchesSafely(final TextView textView) {
return stringMatcher.matches(textView.getError().toString());
}
};
}
}


# Maching logic is to match the subtext of the textview with only the error message.

#describeTo method only for debug.

# you can use this as your custom matcher in the test case as shown in below.

===================


@Test 

public void testLoginMandatory()
{
    onView(withId(R.id.email_sign_in_button)).perform(click());
    onView(ErrorMatcher.withError(Matchers.
            containsString("The field is required"))).check(matches(isDisplayed()));

}



Source