有没有办法在Espresso中计算具有特定ID的元素?
我可以做onView(withId(R.id.my_id)),但后来我被卡住了.
我有一个LinearLayout,我注入元素(不是ListView),我想测试多少或那些是检查它们是否符合预期的行为.
最佳答案 这是我想出的匹配器:
public static Matcher<View> withViewCount(final Matcher<View> viewMatcher, final int expectedCount) {
return new TypeSafeMatcher<View>() {
int actualCount = -1;
@Override
public void describeTo(Description description) {
if (actualCount >= 0) {
description.appendText("With expected number of items: " + expectedCount);
description.appendText("\n With matcher: ");
viewMatcher.describeTo(description);
description.appendText("\n But got: " + actualCount);
}
}
@Override
protected boolean matchesSafely(View root) {
actualCount = 0;
Iterable<View> iterable = TreeIterables.breadthFirstViewTraversal(root);
actualCount = Iterables.size(Iterables.filter(iterable, withMatcherPredicate(viewMatcher)));
return actualCount == expectedCount;
}
};
}
private static Predicate<View> withMatcherPredicate(final Matcher<View> matcher) {
return new Predicate<View>() {
@Override
public boolean apply(@Nullable View view) {
return matcher.matches(view);
}
};
}
用法是:
onView(isRoot()).check(matches(withViewCount(withId(R.id.anything), 5)));