咖啡计数元素 [英] Espresso count elements

查看:73
本文介绍了咖啡计数元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Espresso中是否可以对具有特定ID的元素进行计数?

Is there a way to count elements with a certain id in Espresso?

我可以执行onView(withId(R.id.my_id)),但是我被卡住了.

I can do onView(withId(R.id.my_id)) but then I'm stuck.

我有一个LinearLayout,可以在其中注入元素(而不是ListView),并且我想测试有多少个元素,以检查它们是否符合预期的行为.

I have a LinearLayout where I inject elements (not a ListView), and I want to test how many or those are to check whether they match expected behavior.

推荐答案

这是我想到的匹配器:

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

这篇关于咖啡计数元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆