咖啡计数元素

Gab*_*tin 6 android android-espresso

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

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

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

Be_*_*ive 4

这是我想出的匹配器:

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);
            }
        };
    }
Run Code Online (Sandbox Code Playgroud)

用法是:

onView(isRoot()).check(matches(withViewCount(withId(R.id.anything), 5)));
Run Code Online (Sandbox Code Playgroud)

  • 升级到 Espresso 3.0.0 后,我遇到了 Iterables 问题。导入从 android.support.test.espresso.core.deps.guava.collect.Iterables 更改;到 android.support.test.espresso.core.internal.deps.guava.collect.Iterables;这样做会丢失此代码所需的 .size 。 (2认同)