Approve the correct number of items in a list with espresso

What is the best way to verify and claim that the listview is the expected size of the android endpoint?

I wrote this matches, but I don’t know how to integrate it into the test.

public static Matcher<View> withListSize (final int size) { return new TypeSafeMatcher<View> () { @Override public boolean matchesSafely (final View view) { return ((ListView) view).getChildCount () == size; } @Override public void describeTo (final Description description) { description.appendText ("ListView should have " + size + " items"); } }; } 
+6
source share
2 answers

Figured it out.

 class Matchers { public static Matcher<View> withListSize (final int size) { return new TypeSafeMatcher<View> () { @Override public boolean matchesSafely (final View view) { return ((ListView) view).getCount () == size; } @Override public void describeTo (final Description description) { description.appendText ("ListView should have " + size + " items"); } }; } } 

If one item in the list is expected, put it in the actual test script.

 onView (withId (android.R.id.list)).check (ViewAssertions.matches (Matchers.withListSize (1))); 
+13
source

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 { // 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; } } 

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.
+4
source

Source: https://habr.com/ru/post/987615/


All Articles