android tutorial - Custom matcher for testing TextView in Android Espresso | Developer android - android app development - android studio - android app developement



Example of Custom matcher for testing TextView error message

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

    @NonNull
    public static Matcher<View> withError(final String expectedErrorText) {
        Checks.checkNotNull(expectedErrorText);
        return new BoundedMatcher<View, TextView>(TextView.class) {    
            @Override
            public void describeTo(final Description description) {
                description.appendText("error text: ");
                stringMatcher.describeTo(description);
            }
                
            @Override
            public boolean matchesSafely(final TextView textView) {
                return expectedErrorText.equals(textView.getError().toString());
            }
        };
    }
}
click below button to copy code from our android learning website - android tutorial - team

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.

  • Then you can use your custom matcher in the test case as shown below:
@Test  
public void verifiesSignInErrorIsShown() {
    onView(withId(R.id.email_sign_in_button)).perform(click());
    onView(ErrorMatcher.withError("Your error text")).check(matches(isDisplayed()));
}
click below button to copy code from our android learning website - android tutorial - team

Related Searches to Custom matcher for testing TextView in Android Espresso