在 Espresso 中,我如何测试 RecyclerView 的 *any* child 是否包含正确的文本
In Espresso how can I test if *any* child of RecyclerView contains correct text
我有一个回收站视图,其中应包含顺序未知的 3 个项目。
我知道如何按位置获取回收物品以及如何检查文本
onView(withId(...)).check(匹配(atPosition(0, hasDescendant(withText(A)))));
但我不知道怎么说:if any item hasDescendant(withText(A))
您可以尝试创建自定义 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;
}
};
}
那么你可以这样做:
onView(withId(...)).check(matches(hasItem(hasDescendant(withText(...)))))
或者如果你不想自定义匹配器,你也可以使用 RecyclerViewActions.scrollTo():
onView(withId(...)).perform(scrollTo(hasDescendant(withText(...))))
我有一个回收站视图,其中应包含顺序未知的 3 个项目。
我知道如何按位置获取回收物品以及如何检查文本
onView(withId(...)).check(匹配(atPosition(0, hasDescendant(withText(A)))));
但我不知道怎么说:if any item hasDescendant(withText(A))
您可以尝试创建自定义 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;
}
};
}
那么你可以这样做:
onView(withId(...)).check(matches(hasItem(hasDescendant(withText(...)))))
或者如果你不想自定义匹配器,你也可以使用 RecyclerViewActions.scrollTo():
onView(withId(...)).perform(scrollTo(hasDescendant(withText(...))))