使用浓缩咖啡确认列表中正确数量的项目

时间:2015-05-20 21:55:18

标签: android listview android-espresso

使用android espresso检查并断言listview是预期大小的最佳方法是什么?

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

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

2 个答案:

答案 0 :(得分:21)

想出来了。

p2

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

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

答案 1 :(得分:8)

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

因为 @CoryRoy 已经展示了如何断言它,所以我想告诉你如何使用不同的匹配器获取(返回)数字。

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重复使用。