Skip to content

Commit bcc6f7e

Browse files
author
joe.walnes
committed
Issue 11: Added sensible BaseMatcher.toString() method. Created StringDescription.asString() alias. (Suggested by David Saff)
1 parent 2402c1e commit bcc6f7e

4 files changed

Lines changed: 36 additions & 0 deletions

File tree

‎CHANGES.txt‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@
1111

1212
* StringBuilder can use any Appendable (not just StringBuffer).
1313

14+
* Added sensible toString() method to BaseMatcher.
15+
16+
* Created StringDescription.asString() alias (because toString() caused issues
17+
with static imports).
18+
1419
* Generator recognizes @Factory methods that return subclass of Matcher.
1520
(Fix by David Saff)
1621

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,8 @@ public final void _dont_implement_Matcher___instead_extend_BaseMatcher_() {
1616
// See Matcher interface for an explanation of this method.
1717
}
1818

19+
@Override
20+
public String toString() {
21+
return StringDescription.toString(this);
22+
}
1923
}

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,13 @@ public static String toString(SelfDescribing selfDescribing) {
3737
return description.toString();
3838
}
3939

40+
/**
41+
* Alias for {@link #toString(SelfDescribing)}.
42+
*/
43+
public static String asString(SelfDescribing selfDescribing) {
44+
return toString(selfDescribing);
45+
}
46+
4047
public Description appendText(String text) {
4148
append(text);
4249
return this;
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package org.hamcrest;
2+
3+
import junit.framework.TestCase;
4+
5+
public class BaseMatcherTest extends TestCase {
6+
7+
public void testDescribesItselfWithToStringMethod() {
8+
Matcher someMatcher = new BaseMatcher() {
9+
public boolean matches(Object item) {
10+
throw new UnsupportedOperationException();
11+
}
12+
13+
public void describeTo(Description description) {
14+
description.appendText("SOME DESCRIPTION");
15+
}
16+
};
17+
18+
assertEquals("SOME DESCRIPTION", someMatcher.toString());
19+
}
20+
}

0 commit comments

Comments
 (0)