3

I have a recycler view which should contain 3 items in an unknown order.

I know how to get a recycled item by position and how to check for text

onView(withId(...)).check(matches(atPosition(0, hasDescendant(withText(A)))));

But I don't know how I can say: if any item hasDescendant(withText(A))

Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124

1 Answers1

3

You can try to create a custom Matcher<View>:

public static Matcher<View> hasItem(Matcher<View> matcher) {
    return new BoundedMatcher<View, RecyclerView>(RecyclerView.class) {

        @Override public void describeTo(Description description) {
            description.appendText("has item: ");
            matcher.describeTo(description);
        }

        @Override protected boolean matchesSafely(RecyclerView view) {
            RecyclerView.Adapter adapter = view.getAdapter();
            for (int position = 0; position < adapter.getItemCount(); position++) {
                int type = adapter.getItemViewType(position);
                RecyclerView.ViewHolder holder = adapter.createViewHolder(view, type);
                adapter.onBindViewHolder(holder, position);
                if (matcher.matches(holder.itemView)) {
                    return true;
                }
            }
            return false;
        }
    };
}

Then you can do:

onView(withId(...)).check(matches(hasItem(hasDescendant(withText(...)))))

Or if you do not want a custom matcher, you can also use RecyclerViewActions.scrollTo():

onView(withId(...)).perform(scrollTo(hasDescendant(withText(...))))
Aaron
  • 3,764
  • 2
  • 8
  • 25