Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count RecyclerView items with Espresso

Using Espresso and Hamcrest,

How can I count items number available in a recyclerView?

Exemple: I would like check if 5 items are displaying in a specific RecyclerView (scrolling if necessary).

like image 728
Boris S. Avatar asked Apr 04 '16 10:04

Boris S.


1 Answers

Here an example ViewAssertion to check RecyclerView item count

public class RecyclerViewItemCountAssertion implements ViewAssertion {   private final int expectedCount;    public RecyclerViewItemCountAssertion(int expectedCount) {     this.expectedCount = expectedCount;   }    @Override   public void check(View view, NoMatchingViewException noViewFoundException) {     if (noViewFoundException != null) {         throw noViewFoundException;     }      RecyclerView recyclerView = (RecyclerView) view;     RecyclerView.Adapter adapter = recyclerView.getAdapter();     assertThat(adapter.getItemCount(), is(expectedCount));   } } 

and then use this assertion

onView(withId(R.id.recyclerView)).check(new RecyclerViewItemCountAssertion(5)); 

I have started to write an library which should make testing more simple with espresso and uiautomator. This includes tooling for RecyclerView action and assertions. https://github.com/nenick/espresso-macchiato See for example EspRecyclerView with the method assertItemCountIs(int)

like image 82
nenick Avatar answered Oct 11 '22 08:10

nenick