Android Espresso - check if text doesn't exist in RecyclerView

Viewed 3278

I have the code which checks if the row with text "Product" exists in RecyclerView:

onView(withId(R.id.rv_list)).perform(scrollTo(hasDescendant(withText("Product"))));
onView(withItemText("Product")).check(matches(isDisplayed()));

public static Matcher<View> withItemText(final String itemText) {
    checkArgument(!TextUtils.isEmpty(itemText), "itemText cannot be null or empty");
    return new TypeSafeMatcher<View>() {
        @Override
        public boolean matchesSafely(View item) {
            return allOf(
                    isDescendantOfA(isAssignableFrom(RecyclerView.class)),
                    withText(itemText)).matches(item);
        }
        @Override
        public void describeTo(Description description) {
            description.appendText("is isDescendantOfA RV with text " + itemText);
        }
    };
}

How to check if there is no row with provided text in all list from RecylerView?

1 Answers

You could try create a custom matcher to iterate RecyclerView items:

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;
        }
    };
}

And if you'd like to check if there's no row with specific text, you could do:

onView(withId(R.id.rv_list)).check(matches(not(hasItem(hasDescendant(withText("Product"))))));
Related