Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Espresso count elements

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

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

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.

like image 542
Gabriel Sanmartin Avatar asked Sep 06 '16 12:09

Gabriel Sanmartin


1 Answers

Here is the matcher that I came up with:

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

and the usage is:

onView(isRoot()).check(matches(withViewCount(withId(R.id.anything), 5)));
like image 158
Be_Negative Avatar answered Oct 01 '22 08:10

Be_Negative