3
有沒有一種方法來計算特濃咖啡中的特定ID的元素?咖啡計數元素
我可以做onView(withId(R.id.my_id))
但後來我卡住了。
我有一個LinearLayout我注入元素(不是ListView),我想測試多少或那些是否它們匹配預期的行爲。
有沒有一種方法來計算特濃咖啡中的特定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)));
我升級到3.0.0濃咖啡後,具有與該Iterables的問題。導入從android.support.test.espresso.core.deps.guava.collect.Iterables更改;到android.support.test.espresso.core.internal.deps.guava.collect.Iterables;並在這樣做,失去了這個代碼所需的大小。 –