浓咖啡计数元素

时间:2016-09-06 12:47:18

标签: android android-espresso

有没有办法在Espresso中计算具有特定ID的元素?

我可以做onView(withId(R.id.my_id)),但后来我被困住了。

我有一个LinearLayout,我注入元素(不是ListView),我想测试多少或那些是检查它们是否符合预期的行为。

2 个答案:

答案 0 :(得分:2)

这是我想出的匹配器:

public static Matcher<View> withViewCount(final Matcher<View> viewMatcher, final int expectedCount) {
        return new TypeSafeMatcher<View>() {
            int actualCount = -1;

            @Override
            public void describeTo(Description description) {
                if (actualCount >= 0) {
                    description.appendText("With expected number of items: " + expectedCount);
                    description.appendText("\n With matcher: ");
                    viewMatcher.describeTo(description);
                    description.appendText("\n But got: " + actualCount);
                }
            }

            @Override
            protected boolean matchesSafely(View root) {
                actualCount = 0;
                Iterable<View> iterable = TreeIterables.breadthFirstViewTraversal(root);
                actualCount = Iterables.size(Iterables.filter(iterable, withMatcherPredicate(viewMatcher)));
                return actualCount == expectedCount;
            }
        };
    }

    private static Predicate<View> withMatcherPredicate(final Matcher<View> matcher) {
        return new Predicate<View>() {
            @Override
            public boolean apply(@Nullable View view) {
                return matcher.matches(view);
            }
        };
    }

,用法是:

onView(isRoot()).check(matches(withViewCount(withId(R.id.anything), 5)));

答案 1 :(得分:0)

这可以通过自定义匹配器来实现。您可以通过以下方式在Kotlin中定义一个:

fun withChildViewCount(count: Int, childMatcher: Matcher<View>): Matcher<View> {

    return object : BoundedMatcher<View, ViewGroup>(ViewGroup::class.java) {
        override fun matchesSafely(viewGroup: ViewGroup): Boolean {
            val matchCount = viewGroup.getChildViews()
                    .filter { childMatcher.matches(it) }
                    .count()
            return matchCount == count
        }

        override fun describeTo(description: Description) {
            description.appendText("with child count $count")
        }

    }
}