I am using RecyclerView and i need to get the total count of items in the RecyclerView using android espresso. How can i do it ?
I would do it like this:
@Rule
public ActivityTestRule<MyClass> activityRule = new ActivityTestRule(MyActivity.class);
@Test
public void myTest() {
RecyclerView recyclerView = activityRule.getActivity().findViewById(R.id.my_recyclerview)
int itemCount = recyclerView.getAdapter().getItemCount();
}
While Thekarlo95's answer specifically and fully answers the question, I would like to show my example on how to use his method together with Stéphane's method to test a difference in count before and after specific action:
@Test
public void FilterClickShouldChangeRecyclerViewCount() {
// Get items count before action
RecyclerView recyclerView = mActivityTestRule.getActivity().findViewById(R.id.recycler_view);
int countBefore = Objects.requireNonNull(recyclerView.getAdapter()).getItemCount();
Log.e("count", "Items count before: " + countBefore);
// Perform action
ViewInteraction actionMenuItemView = onView(
allOf(
withId(R.id.action_filter),
withContentDescription("Show Favorites")));
actionMenuItemView.perform(click());
// Verify that items count has changed
onView(withId(R.id.recycler_view))
// Instead of 'not', you can use any other hamcrest Matcher like 'is', 'lessThan' etc.
.check(new RecyclerViewItemCountAssertion(not(countBefore)));
}
And below is a code for RecyclerViewItemCountAssertion
class (just put it on a separate file). Note there are two constructors available:
RecyclerViewItemCountAssertion(int expectedCount)
- parameter of type integer is expected, default is
matcher is used. RecyclerViewItemCountAssertion(Matcher<Integer> matcher)
- parameter of type Matcher<Integer>
is expected, like is(3)
, lessThan(4)
etc.
public class RecyclerViewItemCountAssertion implements ViewAssertion { private final Matcher<Integer> matcher; public RecyclerViewItemCountAssertion(int expectedCount) { this.matcher = is(expectedCount); } public RecyclerViewItemCountAssertion(Matcher<Integer> 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(); assert adapter != null; assertThat(adapter.getItemCount(), matcher); } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.