用 espresso 断言列表中的正确数量的项目

Assert proper number of items in list with espresso

检查和断言列表视图是 android espresso 的预期大小的最佳方法是什么?

我写了这个匹配器,但不太清楚如何将它集成到测试中。

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");
        }
    };
}

想通了。

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");
      }
    };
  }
}

如果需要列表中的一项,请将其放入实际测试脚本中。

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

有两种不同的方法可以使用 espresso 计算列表中的项目数: 第一个是上面提到的 @CoryRoy - 使用 TypeSafeMatcher,另一个是使用 BoundedMatcher.

并且因为 @CoryRoy 已经展示了如何断言它,在这里我想告诉你如何使用不同的匹配器来获取(return)数字。

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

}

还想提一下,您应该使用 ListView#getCount() 而不是 ListView#getChildCount():

  • getCount() - 适配器拥有的数据项数,可能大于可见视图数。
  • getChildCount() - ViewGroup 中的子项数量,可能会被 ViewGroup 重用。