0

I can use view actions to perform click on individual list items

onView(withId(R.id.rv_recycler_view))
                .perform(actionOnItemAtPosition(0, click()));

However, I want to return the number of list items, and use a loop to click on each list item without writing a separate pice of code for each item.

How can I return the number of list items the recycler view contains? Maybe I need to access the adapter variable through the activity directly?

Thanks

the_prole
  • 8,275
  • 16
  • 78
  • 163

1 Answers1

0

I would stub out the dependency so that you can control your test environment, i.e. If you feed in 3 items, you should expect that three items are displayed. You can check this with the custom action by nenick How to count RecyclerView items with Espresso

public class CustomRecyclerViewAssertions {
//Asserts the number of items in a RecyclerView

   public static ViewAssertion AssertItemCount(final int expectedCount) {
     return new ViewAssertion() {
       @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));
       }
     };
  }
}

which is called by using

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

Once you know how many items are present, you can use:

onView(withId(R.id.recyclerView)).perform(
        actionOnItemAtPosition<RecyclerView.ViewHolder>(1, click()))

As the recyclerView is showing multiple instances of the same view, I wouldn't waste time duplicating code to click each item

Emmaaa
  • 300
  • 2
  • 7
  • Seems overly complicated, and I'm not asserting a number, I'm checking one. Why can't i Just call `adapter.getItemCount()` and use a loop to click over each item using the loop index? – the_prole Aug 23 '17 at 16:34