Espresso - Check RecyclerView items are ordered correctly

后端 未结 5 2064
一个人的身影
一个人的身影 2021-01-05 03:18

How to go about checking whether RecyclerView items are displayed in the correct order using Espresso? I\'m trying to test it checking it by the text for the title of each e

5条回答
  •  生来不讨喜
    2021-01-05 03:43

    I simplified a bit Mosius answer:

    public static Matcher hasItemAtPosition(final Matcher matcher, final int position) {
        return new BoundedMatcher(RecyclerView.class) {
            @Override
            public void describeTo(Description description) {
                description.appendText("has item at position " + position + ": ");
                matcher.describeTo(description);
            }
            @Override
            protected boolean matchesSafely(RecyclerView recyclerView) {
                RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(position);
                return matcher.matches(viewHolder.itemView);
            }
        };
    }
    

    We pass Matcher to the function so we can provide further conditions. Example usage:

    onView(hasItemAtPosition(hasDescendant(withText("Item 1")), 0)).check(matches(isDisplayed()));
    onView(hasItemAtPosition(hasDescendant(withText("Item 2")), 1)).check(matches(isDisplayed()));
    

提交回复
热议问题