Có hai phương pháp khác nhau để nhận được sản phẩm đếm trong một danh sách với espresso: Đầu tiên là như @CoryRoy nêu trên - sử dụng TypeSafeMatcher, một trong những khác là sử dụng BoundedMatcher.
Và bởi vì @CoryRoy đã cho thấy cách xác nhận điều đó, ở đây tôi muốn nói cách nhận (trả lại) số sử dụng các trình so khớp khác nhau.
public class CountHelper {
private static int count;
public static int getCountFromListUsingTypeSafeMatcher(@IdRes int listViewId) {
count = 0;
Matcher matcher = new TypeSafeMatcher<View>() {
@Override
protected boolean matchesSafely(View item) {
count = ((ListView) item).getCount();
return true;
}
@Override
public void describeTo(Description description) {
}
};
onView(withId(listViewId)).check(matches(matcher));
int result = count;
count = 0;
return result;
}
public static int getCountFromListUsingBoundedMatcher(@IdRes int listViewId) {
count = 0;
Matcher<Object> matcher = new BoundedMatcher<Object, String>(String.class) {
@Override
protected boolean matchesSafely(String item) {
count += 1;
return true;
}
@Override
public void describeTo(Description description) {
}
};
try {
// do a nonsense operation with no impact
// because ViewMatchers would only start matching when action is performed on DataInteraction
onData(matcher).inAdapterView(withId(listViewId)).perform(typeText(""));
} catch (Exception e) {
}
int result = count;
count = 0;
return result;
}
}
Cũng muốn đề cập rằng bạn nên sử dụng ListView#getCount()
thay vì ListView#getChildCount()
:
getCount()
- số mục dữ liệu thuộc sở hữu của Adaptor, mà có thể lớn hơn số lượng ảnh nhìn thấy được.
getChildCount()
- số lượng trẻ em trong ViewGroup, có thể được sử dụng lại bởi ViewGroup.
Nguồn
2016-06-12 17:24:04
Nếu cà phê espresso ngon, mọi thứ trong danh sách không quan trọng. Bây giờ đi cho một. –