Skip to content

Instantly share code, notes, and snippets.

@acontal
Created February 16, 2014 18:14
Show Gist options
  • Save acontal/9038375 to your computer and use it in GitHub Desktop.
Save acontal/9038375 to your computer and use it in GitHub Desktop.
[android][espresso] Assert that a View contains a given number of matching views.
/**
* Sugar for has(int, isAssignableFrom(Class)).
*
* Example: onView(rootView).check(has(3, EditText.class);
*/
public static ViewAssertion has(final int expectedCount, Class<? extends View> clazz) {
return has(expectedCount, isAssignableFrom(clazz));
}
/**
* Returns a generic {@link ViewAssertion} that asserts that there is a
* given number of descendant views that match the specified matcher.
*
* Example: onView(rootView).check(has(3, isAssignableFrom(EditText.class));
*
* @param expectedCount the number of descendant views that should match the specified matcher
* @param selector the matcher to select the descendant views
* @throws AssertionError if the number of views that match the selector is different from expectedCount
*/
public static ViewAssertion has(final int expectedCount, final Matcher<View> selector) {
return new ViewAssertion() {
@Override
public void check(Optional<View> view, Optional<NoMatchingViewException> noViewFoundException) {
checkArgument(view.isPresent());
View rootView = view.get();
Iterable<View> descendantViews = breadthFirstViewTraversal(rootView);
List<View> selectedViews = new ArrayList<View>();
for (View descendantView : descendantViews) {
if (selector.matches(descendantView)) {
selectedViews.add(descendantView);
}
}
if (selectedViews.size() != expectedCount) {
String errorMessage = HumanReadables.getViewHierarchyErrorMessage(rootView,
Optional.of(selectedViews),
String.format("Found %d views instead of %d matching: %s", selectedViews.size(), expectedCount, selector),
Optional.of("****MATCHES****"));
throw new AssertionFailedError(errorMessage);
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment