Espresso - how to find a specific item in a recycler view (order is random)
I was able to get this to work doing the following:
Matcher<RecyclerView.ViewHolder> matcher = CustomMatcher.withTitle("A");
onView((withId(R.id.recycler_view))).perform(scrollToHolder(matcher), actionOnHolderItem(matcher, click()));
Where CustomMatcher.withTitle
is:
public static Matcher<RecyclerView.ViewHolder> withTitle(final String title)
{
return new BoundedMatcher<RecyclerView.ViewHolder, CustomListAdapter.ItemViewHolder>(CustomListAdapter.ItemViewHolder.class)
{
@Override
protected boolean matchesSafely(CustomListAdapter.ItemViewHolder item)
{
return item.mTitleView.getText().toString().equalsIgnoreCase(title);
}
@Override
public void describeTo(Description description)
{
description.appendText("view holder with title: " + title);
}
};
}
You don't need a custom matcher for this, just use this
onView(withId(R.id.recycler_id)).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText("A")), click()));
and add espresso-contrib dependency
androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:<espressso-version>'
Or if you're using AndroidX
androidTestImplementation 'androidx.test.espresso:espresso-contrib:<espressso-version>'