Counting views in Espresso

Alexey Alter-Pesotskiy
testableapple
Published in
2 min readJan 26, 2020

This Note originally published on my Personal Blog here. Read original note so that you won’t miss any content.

While doing pretty and flexible things with Espresso, have you ever faced with AmbiguousViewMatcherException? If so, go on reading, if no, you are lucky man, just keep the article (:

When does this exception appear? Imagine, you have a RecyclerView with a lot of elements and some of them have the same resource-id as the neighbours have. Do you wanna count the specific element? Do you wanna tap on the first/last specific element? Do you wanna grep the elements by positions? You are more than welcome to stumble on the AmbiguousViewMatcherException!

Let’s try to play around it. I’ll show my vision, how to cover this exception and get a profit. Here we go!

The first way

Is to create the object, that will handle the exception and grep a hierarchy of the views. It will give us an opportunity to get:

  • the first matching view;
  • the last matching view;
  • matching view at position;
  • the count of matching views.

Comments:

I see only one con: it limits us to the views, that we are considering at the moment, and hides from us everything that is outside the screen.

Showcase:

The second way

Is to create two classes:

1. The first class will match the RecyclerView. It will give us an opportunity to parse the RecyclerView and to get:

  • matching view at position;
  • any view at position.

2. The second class will handle the AmbiguousViewMatcherException and grep a hierarchy of the whole RecyclerView. Thanks to it we’ll be able to get:

  • the first matching view;
  • the last matching view;
  • the count of matching views;
  • the possibility to consider all the views inside and outside the screen.

Comments:

This way is a bit more complicated, but definitely more flexible and reliable. Also, it «almost» doesn’t contradict the Espresso paradigm (:

Showcase:

Conclusion

The AmbiguousViewMatcherException and counting views in Espresso are not the problems anymore.

Wish you happy Mondays (:

--

--