How to count RecyclerView items with Espresso

后端 未结 7 1108
时光说笑
时光说笑 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:12

    Adding a bit of syntax sugar to the @Stephane's answer.

    public class RecyclerViewItemCountAssertion implements ViewAssertion {
        private final Matcher matcher;
    
        public static RecyclerViewItemCountAssertion withItemCount(int expectedCount) {
            return withItemCount(is(expectedCount));
        }
    
        public static RecyclerViewItemCountAssertion withItemCount(Matcher matcher) {
            return new RecyclerViewItemCountAssertion(matcher);
        }
    
        private 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:

        import static your.package.RecyclerViewItemCountAssertion.withItemCount;
    
        onView(withId(R.id.recyclerView)).check(withItemCount(5));
        onView(withId(R.id.recyclerView)).check(withItemCount(greaterThan(5)));
        onView(withId(R.id.recyclerView)).check(withItemCount(lessThan(5)));
        // ...
    

提交回复
热议问题