Skip to content

Commit edc4605

Browse files
author
smgfreeman
committed
Issue 68. IsInstanceOf reports actual class on mismatch
1 parent 359c3ca commit edc4605

2 files changed

Lines changed: 19 additions & 4 deletions

File tree

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

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,16 @@
22
*/
33
package org.hamcrest.core;
44

5-
import org.hamcrest.BaseMatcher;
65
import org.hamcrest.Description;
6+
import org.hamcrest.DiagnosingMatcher;
77
import org.hamcrest.Factory;
88
import org.hamcrest.Matcher;
99

1010

1111
/**
1212
* Tests whether the value is an instance of a class.
1313
*/
14-
public class IsInstanceOf extends BaseMatcher<Object> {
14+
public class IsInstanceOf extends DiagnosingMatcher<Object> {
1515
private final Class<?> theClass;
1616

1717
/**
@@ -24,8 +24,19 @@ public IsInstanceOf(Class<?> theClass) {
2424
this.theClass = theClass;
2525
}
2626

27-
public boolean matches(Object item) {
28-
return theClass.isInstance(item);
27+
@Override
28+
protected boolean matches(Object item, Description mismatchDescription) {
29+
if (null == item) {
30+
mismatchDescription.appendText("null");
31+
return false;
32+
}
33+
34+
if (!theClass.isInstance(item)) {
35+
mismatchDescription.appendText("[" + item.getClass().getSimpleName() + "] ").appendValue(item);
36+
return false;
37+
}
38+
39+
return true;
2940
}
3041

3142
public void describeTo(Description description) {

‎hamcrest-unit-test/src/main/java/org/hamcrest/core/IsInstanceOfTest.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@ public void testHasAReadableDescription() {
2626
assertDescription("an instance of java.lang.Number", instanceOf(Number.class));
2727
}
2828

29+
public void testDecribesActualClassInMismatchMessage() {
30+
assertMismatchDescription("[String] \"some text\"", instanceOf(Number.class), "some text");
31+
}
32+
2933
public void testInstanceOfRequiresACastToReturnTheCorrectTypeForUseInJMock() {
3034
@SuppressWarnings("unused")
3135
Integer anInteger = (Integer)with(instanceOf(Integer.class));

0 commit comments

Comments
 (0)