Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

attempt to improve the mismatch description of the hasItem/hasItems m…

…atchers
  • Loading branch information...
commit 96e113d7995eac6725e4d5ec780560ca8ff6ae49 1 parent 8dd870c
@scarytom scarytom authored
View
18 hamcrest-core/src/main/java/org/hamcrest/core/IsCollectionContaining.java
@@ -20,17 +20,31 @@ public IsCollectionContaining(Matcher<? super T> elementMatcher) {
@Override
protected boolean matchesSafely(Iterable<? super T> collection, Description mismatchDescription) {
- boolean isPastFirst = false;
+ boolean empty = true;
for (Object item : collection) {
- if (elementMatcher.matches(item)){
+ empty = false;
+ if (elementMatcher.matches(item)) {
return true;
}
+ }
+
+ if (empty) {
+ mismatchDescription.appendText("was an empty collection");
+ return false;
+ }
+
+ mismatchDescription.appendText("was a collection that did not contain ")
+ .appendDescriptionOf(elementMatcher)
+ .appendText(" -- mismatches were: [");
+ boolean isPastFirst = false;
+ for (Object item : collection) {
if (isPastFirst) {
mismatchDescription.appendText(", ");
}
elementMatcher.describeMismatch(item, mismatchDescription);
isPastFirst = true;
}
+ mismatchDescription.appendText("]");
return false;
}
View
11 hamcrest-unit-test/src/main/java/org/hamcrest/collection/IsCollectionContainingTest.java
@@ -32,11 +32,11 @@ public void testMatchesACollectionThatContainsAnElementMatchingTheGivenMatcher()
public void testDoesNotMatchCollectionThatDoesntContainAnElementMatchingTheGivenMatcher() {
final Matcher<Iterable<? super String>> matcher1 = hasItem(mismatchable("a"));
- assertMismatchDescription("mismatched: b, mismatched: c", matcher1, asList("b", "c"));
-
+ assertMismatchDescription("was a collection that did not contain mismatchable: a -- mismatches were: [mismatched: b, mismatched: c]",
+ matcher1, asList("b", "c"));
final Matcher<Iterable<? super String>> matcher2 = hasItem(equalTo("a"));
- assertMismatchDescription("", matcher2, new ArrayList<String>());
+ assertMismatchDescription("was an empty collection", matcher2, new ArrayList<String>());
}
public void testDoesNotMatchNull() {
@@ -84,9 +84,10 @@ public void testMatchesAllItemsInCollection() {
}
public void testReportsMismatchWithAReadableDescription() {
- final Matcher<Iterable<Integer>> matcher = hasItems(1, 4);
+ final Matcher<Iterable<Integer>> matcher = hasItems(3, 4);
- assertMismatchDescription("a collection containing <4> was <1>, was <2>, was <3>", matcher, asList(1, 2, 3));
+ assertMismatchDescription("a collection containing <4> was a collection that did not contain <4> -- mismatches were: [was <1>, was <2>, was <3>]",
+ matcher, asList(1, 2, 3));
}
private static Matcher<? super String> mismatchable(final String string) {
Please sign in to comment.
Something went wrong with that request. Please try again.