Skip to content

Commit 38b2ca6

Browse files
committed
Better mismatch description for TypeSafeDiagnosingMatcher
1 parent 5e51a70 commit 38b2ca6

2 files changed

Lines changed: 38 additions & 3 deletions

File tree

‎hamcrest-core/src/main/java/org/hamcrest/TypeSafeDiagnosingMatcher.java‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,14 @@ public final boolean matches(Object item) {
6060
@SuppressWarnings("unchecked")
6161
@Override
6262
public final void describeMismatch(Object item, Description mismatchDescription) {
63-
if (item == null || !expectedType.isInstance(item)) {
64-
super.describeMismatch(item, mismatchDescription);
65-
} else {
63+
if (item == null) {
64+
mismatchDescription.appendText("was null");
65+
} else if (!expectedType.isInstance(item)) {
66+
mismatchDescription.appendText("was ")
67+
.appendText(item.getClass().getSimpleName())
68+
.appendText(" ")
69+
.appendValue(item);
70+
} else {
6671
matchesSafely((T) item, mismatchDescription);
6772
}
6873
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package org.hamcrest;
2+
3+
import org.junit.Test;
4+
5+
import static org.hamcrest.AbstractMatcherTest.assertMismatchDescription;
6+
7+
/**
8+
* @author Steve Freeman 2016 http://www.hamcrest.com
9+
*/
10+
public class TypeSafeDiagnosingMatcherTest {
11+
12+
private final TypeSafeDiagnosingMatcher matcher = new TypeSafeDiagnosingMatcher<String>() {
13+
@Override
14+
protected boolean matchesSafely(String item, Description mismatchDescription) {
15+
mismatchDescription.appendText("mismatching");
16+
return false;
17+
}
18+
19+
@Override
20+
public void describeTo(Description description) { }
21+
};
22+
23+
24+
@Test public void
25+
describesMismatches() {
26+
assertMismatchDescription("was null", matcher, null);
27+
assertMismatchDescription("was Character \"c\"", matcher, 'c');
28+
assertMismatchDescription("mismatching", matcher, "other");
29+
}
30+
}

0 commit comments

Comments
 (0)