Friday, 22 January 2016

How to Create Custom Matcher in Espresso?

Espresso allows us to create our own custom matcher and according to me it is really useful for automation. I use many custom matchers once I learn how to use it as it gives me flexibility in automating different functionality.

Video Tutorial -

Testing Scenario- > 
You want to test a Simple login screen and check if negative input or no input is given then it displays Error Message as shown in figure.
Espresso Custom Matcher Example
Espresso Custom Matcher Example

The effective way of testing this is using custome matcher. Let us see how to create a custom matcher
1. Create a class name ErrorMatcher inside androidTest folder with below code

public class ErrorMatcher {


 public static Matcher<View> withError(final Matcher<String> stringMatcher) {

            return new BoundedMatcher<View, TextView>(TextView.class) {


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


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

2. Matching logic is to match the subset of TextView with only error messages.
3.  describeTo method is for debug output.
4. Then you can use your custom matcher in the test case as shown below


public void testLoginMandatory()
            containsString("The field is required"))).check(matches(isDisplayed()));

I hope this post helps you find your code coverage for your test suit :)
Please Share your feedback in comments section below and follow QA Automated to get latest post update.Happy Testing :-)

1 comment: