如何在Espresso的RecyclizerView中断言?

2022-08-31 13:43:05

我正在使用espresso-contrib对执行操作,并且它按预期工作,例如:RecyclerView

//click on first item
onView(withId(R.id.recycler_view))
    .perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));

我需要对它执行断言。像这样:

onView(withId(R.id.recycler_view))
    .perform(
        RecyclerViewActions.actionOnItemAtPosition(
            0, check(matches(withText("Test Text")))
        )
    );

但是,由于RecyclerViewActions当然期待一个动作,所以它说了错误的第二个参数类型。没有浓缩咖啡。RecyclerViewAssertions

有没有办法对 执行断言?RecyclerView


答案 1

非常简单。不需要额外的库。狐狸

    onView(withId(R.id.recycler_view))
            .check(matches(atPosition(0, withText("Test Text"))));

如果您的 ViewHolder 使用 ViewGroup,请使用 like 换行:withText()hasDescendant()

onView(withId(R.id.recycler_view))
                .check(matches(atPosition(0, hasDescendant(withText("Test Text")))));

你可以把方法放进你的班级。Utils

public static Matcher<View> atPosition(final int position, @NonNull final Matcher<View> itemMatcher) {
    checkNotNull(itemMatcher);
    return new BoundedMatcher<View, RecyclerView>(RecyclerView.class) {
        @Override
        public void describeTo(Description description) {
            description.appendText("has item at position " + position + ": ");
            itemMatcher.describeTo(description);
        }

        @Override
        protected boolean matchesSafely(final RecyclerView view) {
            RecyclerView.ViewHolder viewHolder = view.findViewHolderForAdapterPosition(position);
            if (viewHolder == null) {
                // has no item on such position
                return false;
            }
            return itemMatcher.matches(viewHolder.itemView);
        }
    };
}

如果您的项目最初可能在屏幕上不可见,请在以下时间之前滚动到它:

    onView(withId(R.id.recycler_view))
            .perform(scrollToPosition(87))
            .check(matches(atPosition(87, withText("Test Text"))));

答案 2

您应该查看Danny Roa的解决方案 自定义回收器查看操作 并像这样使用它:

onView(withRecyclerView(R.id.recycler_view)
    .atPositionOnView(1, R.id.ofElementYouWantToCheck))
    .check(matches(withText("Test text")));

推荐