There are two different approaches to counting items on an espresso list: The first is like @CoryRoy, mentioned above using TypeSafeMatcher , the other to use BoundedMatcher .
And since @CoryRoy already showed how to state it, here I would like to tell how to get (return) a number using different comparisons.
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 {
I also want to mention that you should use ListView#getCount() instead of ListView#getChildCount() :
getCount() - the number of data elements belonging to the adapter , which may be greater than the number of visible types.getChildCount() - the number of children in the ViewGroup , which can be reused in the ViewGroup.
source share