How to count RecyclerView items with Espresso

后端 未结 7 1113
时光说笑
时光说笑 2020-12-25 09:49

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 Re

7条回答
  •  旧巷少年郎
    2020-12-25 10:19

    To complete nenick answer and provide and little bit more flexible solution to also test if item cout is greaterThan, lessThan ...

    public class RecyclerViewItemCountAssertion implements ViewAssertion {
    
        private final Matcher matcher;
    
        public RecyclerViewItemCountAssertion(int expectedCount) {
            this.matcher = is(expectedCount);
        }
    
        public RecyclerViewItemCountAssertion(Matcher matcher) {
            this.matcher = matcher;
        }
    
        @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(), matcher);
        }
    
    }
    

    Usage:

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

提交回复
热议问题