This is not a guide but some samples for writing custom Espresso Matchers to enhance our tests’ scope in Android Dev.
I know that every project has its own world, and things that we can write for a particular one aren’t useful for others, but I can assure that custom Espresso Matchers that we write for an specific project, are going to be helpful for another.
Custom Espresso Matchers
Espresso’s API is pretty robust and we can write our own Matchers, that are going to be used by Espresso’s infrastructure keeping the well known path:
The secret to write a custom Matcher is behind understanding what is the job of
BoundedMatcher which is based on Hamcrest’s
BaseMatcher so the
matches()function from above takes a
Matcher<? extends View>
This is all we need to understand, because then the only thing we have to write is to override the
describeTo methods. The first one has the secret: this receives the view in which we want to do the match, i.e a TextView to asserts the text Size or the hint color. With the latter we provide a description for the situation when the assertion fails:
description.appendText("with item hint: " + matcherText);
Now, let me share to you some custom matchers I’ve been constantly using in my projects (some of them developed entirely by me, others an adaptation of some I’ve found and don’t have the info at this moment to give the credits, but let me know in the comments if you consider it’s from you and then I’ll update the article with proper credits) and maybe with the time I’ll be updating the contents of this article with new Matchers I consider important to share.
For this first example I’m going to share the code in both Kotlin and Java, and for the rest, in Java, but you can re-write it in Kotlin, it’s not hard to do it.
Custom Espresso Matcher which checks if a
ListViewhas an specific size
Kotlin (within a companion object):
How to use it?
Custom Espresso Matcher to check the size of a
Goes to an specific position in a RecyclerView, then checks if that item has specific information (i.e an specific text in the holder)
Verifies if a text matches the text of a TextInputLayout hint
Matcher to check the value/progress of a
Verifies if a text matches the text of an EditText hint
Verifies that a
TextView has an specific color
And for the moment that’s all folks. Remember to define the matchers on a Class local to the package on
androidTest in your project. We can together complement this set of custom matchers, let me know in the comments what kind of matcher we can add.