How to count RecyclerView items with Espresso

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

    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)

    0 讨论(0)
提交回复
热议问题