Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Espresso - how to find a specific item in a recycler view (order is random)

I'm wondering how I would be able to find a specific item in a recycler view where the order of items is randomized each run.

Let's assume I have 4 items in the recycler view, each represented by the same type of view holder with a text view in it. A unique title is applied to each view holder/item. For this example let's say the titles are, for simplicity's sake, "A", "B", "C", and "D".

How would I find the position (and then click) item "A" if the order is randomized? I know if the order does not change I could the scrollToPosition RecyclerViewInteraction action, but in this case the order can and will change.

Any thoughts?

like image 387
Zach Avatar asked Jun 09 '16 21:06

Zach


People also ask

How do I select items in RecyclerView in espresso?

To interact with RecyclerViews using Espresso, you can use the espresso-contrib package, which has a collection of RecyclerViewActions that can be used to scroll to positions or to perform actions on items: scrollTo() - Scrolls to the matched View, if it exists.

How does recycler view work internally?

RecyclerView will go to Adapter and request it to create new ViewHolder from the ViewType . Adapter will create a new ViewHolder and bind it with the data for the requested position . Adapter will return ViewHolder to RecyclerView and RecyclerView return the View back to LayoutManger .


1 Answers

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);
        }
    };
}
like image 87
Zach Avatar answered Oct 22 '22 22:10

Zach