Validating views by tag with Espresso

Written with Thainara Rogério

If you work with Android, you will often have to validate a view that is inside a recycler view using Espresso. You would probably do that by writing something like this:

But let’s say the recycler view renders two views with the same text and id. The test would fail because Espresso wouldn’t be able to find an unique view with the matcher provided, since there are two views. You can easily work around this and place a tag in the root view of each cell and make the assert using the tag.

The tag must be unique. For instance, if you are rendering a database object you can use its model id. With this, to validate a view that is inside a cell with the tag 1 , we have the following code:

Now let’s crack the code and find out what the Espresso’s functions do.

allOf can be used to validate a view using more than one matcher. You can chain it infinitely, for example:

isDescendantOfA can be called to execute a matcher against all the view tree above the current view. That means you can execute the match even if your view is inside a ViewGroup that is inside a view where you put the tag.

withTagValue(is((Object)1L))) a simple matcher to validate that the view has the tag 1.

That’s it! Only a few functions later and you can find and validate your desired view.

In this post, we understood how to validate views placed inside a recycler view. However, these Espresso’s functions also work for other purposes, such as repeated views outside of a recycler view or even specify tests to make sure that they are not validating the wrong view.

Thanks Gustavo Freitas for the review.

Show your support

Clapping shows how much you appreciated Jonathan Rafael Zanella’s story.