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:


Writing UI tests:
* Espresso custom matchers

Table Of Contents
2 Gradle
5 Intent
17 Service
19 WebView
31 SQLite
35 Glide
37 Dialog
38 ACRA
44 Handler
53 Toast
63 Menu
65 Picasso
70 Volley
71 Widgets
78 Realm
90 Spinner
93 Writing UI tests
95 OkHttp
108 TextView
109 ListView
111 Loader
118 Xposed
119 Security
121 ImageView
123 Doze Mode
130 Drawables
131 Colors
134 Fresco
139 AdMob
145 Keyboard
146 Button
150 EditText
155 Vk SDK
163 ExoPlayer
169 XMPP
175 OpenCV
177 Threads
184 ORMLite
186 TabLayout
190 LruCache
192 Zip files
194 Fastlane
199 FileIO
202 Moshi
210 VideoView
216 Paint
218 ProGuard
226 CleverTap
228 ADB shell
229 Ping ICMP
230 AIDL
234 Context
240 JCodec
242 Okio
249 FuseView
254 Looper
261 Fastjson
263 Jackson
267 Smartcard