Espresso custom matchers

suggest change

Espresso by default has many matchers that help you find views that you need to do some checks or interactions with them.

Most important ones can be found in the following cheat sheet:

https://google.github.io/android-testing-support-library/docs/espresso/cheatsheet/

Some examples of matchers are:

All of these are very useful for everyday use, but if you have more complex views writing your custom matchers can make the tests more readable and you can reuse them in different places.

There are 2 most common type of matchers you can extend: TypeSafeMatcher BoundedMatcher

Implementing TypeSafeMatcher requires you to check the instanceOf the view you are asserting against, if its the correct type you match some of its properties against a value you provided to a matcher.

For example, type safe matcher that validates an image view has correct drawable:

public class DrawableMatcher extends TypeSafeMatcher<View> {

    private @DrawableRes final int expectedId;
    String resourceName;
    
    public DrawableMatcher(@DrawableRes int expectedId) {
        super(View.class);
        this.expectedId = expectedId;
    }

    @Override
    protected boolean matchesSafely(View target) {
        //Type check we need to do in TypeSafeMatcher
        if (!(target instanceof ImageView)) {
            return false;
        }
        //We fetch the image view from the focused view
        ImageView imageView = (ImageView) target;
        if (expectedId < 0) {
            return imageView.getDrawable() == null;
        }
        //We get the drawable from the resources that we are going to compare with image view source
        Resources resources = target.getContext().getResources();
        Drawable expectedDrawable = resources.getDrawable(expectedId);
        resourceName = resources.getResourceEntryName(expectedId);

        if (expectedDrawable == null) {
            return false;
        }
        //comparing the bitmaps should give results of the matcher if they are equal
        Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
        Bitmap otherBitmap = ((BitmapDrawable) expectedDrawable).getBitmap();
        return bitmap.sameAs(otherBitmap);
    }

    @Override
    public void describeTo(Description description) {
        description.appendText("with drawable from resource id: ");
        description.appendValue(expectedId);
        if (resourceName != null) {
            description.appendText("[");
            description.appendText(resourceName);
            description.appendText("]");
        }
    }
}

Usage of the matcher could be wrapped like this:

public static Matcher<View> withDrawable(final int resourceId) {
  return new DrawableMatcher(resourceId);
}

onView(withDrawable(R.drawable.someDrawable)).check(matches(isDisplayed()));

Bounded matchers are similar you just dont have to do the type check but, since that is done automagically for you:

/**
* Matches a {@link TextInputFormView}'s input hint with the given resource ID
*
* @param stringId
* @return
*/
public static Matcher<View> withTextInputHint(@StringRes final int stringId) {
   return new BoundedMatcher<View, TextInputFormView>(TextInputFormView.class) {
       private String mResourceName = null;

       @Override
       public void describeTo(final Description description) {
           //fill these out properly so your logging and error reporting is more clear
           description.appendText("with TextInputFormView that has hint ");
           description.appendValue(stringId);
           if (null != mResourceName) {
               description.appendText("[");
               description.appendText(mResourceName);
               description.appendText("]");
           }
       }

       @Override
       public boolean matchesSafely(final TextInputFormView view) {
           if (null == mResourceName) {
               try {
                   mResourceName = view.getResources().getResourceEntryName(stringId);
               } catch (Resources.NotFoundException e) {
                   throw new IllegalStateException("could not find string with ID " + stringId, e);
               }
           }
           return view.getResources().getString(stringId).equals(view.getHint());
       }
   };
}

More on matchers can be read up on:

http://hamcrest.org/

https://developer.android.com/reference/android/support/test/espresso/matcher/ViewMatchers.html

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents