Skip to content

Commit 6d06cb3

Browse files
committed
robust implementation of the appendValue method in BaseDescription that does sensible things in the face of an object whose toString method throws an exception. This is in response to issue 184 (on the google code issue tracker).
1 parent 20e8b9c commit 6d06cb3

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

hamcrest-core/src/main/java/org/hamcrest/BaseDescription.java

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,26 +37,35 @@ public Description appendValue(Object value) {
3737
append('"');
3838
} else if (value instanceof Short) {
3939
append('<');
40-
append(valueOf(value));
40+
append(descriptionOf(value));
4141
append("s>");
4242
} else if (value instanceof Long) {
4343
append('<');
44-
append(valueOf(value));
44+
append(descriptionOf(value));
4545
append("L>");
4646
} else if (value instanceof Float) {
4747
append('<');
48-
append(valueOf(value));
48+
append(descriptionOf(value));
4949
append("F>");
5050
} else if (value.getClass().isArray()) {
5151
appendValueList("[",", ","]", new ArrayIterator(value));
5252
} else {
5353
append('<');
54-
append(valueOf(value));
54+
append(descriptionOf(value));
5555
append('>');
5656
}
5757
return this;
5858
}
59-
59+
60+
private String descriptionOf(Object value) {
61+
try {
62+
return valueOf(value);
63+
}
64+
catch (Exception e) {
65+
return value.getClass().getName() + "@" + Integer.toHexString(value.hashCode());
66+
}
67+
}
68+
6069
@Override
6170
public <T> Description appendValueList(String start, String separator, String end, T... values) {
6271
return appendValueList(start, separator, end, Arrays.asList(values));

hamcrest-unit-test/src/main/java/org/hamcrest/BaseDescriptionTest.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,4 +52,16 @@ public void testBracketsAppendedObjectValue() {
5252
baseDescription.appendValue(value);
5353
assertEquals("<" + value.toString() + ">", result.toString());
5454
}
55+
56+
public void testSafelyDescribesAppendedValueOfObjectWhoseToStringThrowsAnException() {
57+
final Object value = new Object() {
58+
@Override public String toString() {
59+
throw new UnsupportedOperationException();
60+
}
61+
};
62+
63+
final String expected = value.getClass().getName() + "@" + Integer.toHexString(value.hashCode());
64+
baseDescription.appendValue(value);
65+
assertEquals("<" + expected + ">", result.toString());
66+
}
5567
}

0 commit comments

Comments
 (0)