Last week I shared a helpful feature in Android Studio — Scratch files. This time, I want to tell you all about how to match items in a Recycler View by title.
If you’re not familiar with it, Espresso is a powerful UI test automation framework for Android. Some things are fairly easy to do — clicking on a particular button looks like this:
However, things get much more complicated when you’re working with RecyclerViews — especially when trying to interact with an item contained inside of one.
Espresso operates under the same restrictions as someone using the phone — if the item isn’t visible on the screen, Espresso can’t click on it or “see” it in order to verify or interact with it. This presents an interesting challenge as your UI tests may work fine on one device, but switching to one with a different screen size can cause your tests can fail unexpectedly.
Fortunately for us, Google has provided some helpful utilities specifically for working with Recycler Views: https://developer.android.com/reference/androidx/test/espresso/contrib/RecyclerViewActions
RecyclerViewActions.actionOnItem() method looks perfect for our purposes, and has the added benefit of automatically scrolling to the right view before trying to act on it — thereby eliminating the unexpected failures due to differences in screen size.
To use this method to find an item based on its title though, we’re going to have to define a ViewMatcher:
Armed with this helpful function, we can now use this matcher like this:
If you’re already using Espresso in your project, the only additional import you need to add to your
build.gradle file is:
Test this out and let me know in the comments what other useful custom Espresso matchers you have defined in your project! And, please follow me on Medium if you’re interested in being notified of future tidbits.
Interested in joining the awesome team here at Intrepid? We’re hiring!
This tidbit was discovered on April 12, 2019.