Search code examples
androidlistviewandroid-espresso

Assert proper number of items in list with espresso


What is the best way to inspect and assert that a listview is the expected size with android espresso?

I wrote this matcher, but don't quite 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");
        }
    };
}

Solution

  • Figured this 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 expecting one item in the list, put this in the actual test script.

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