1 package org.hamcrest; 2 3 import junit.framework.TestCase; 4 import org.junit.Assert; 5 6 public abstract class AbstractMatcherTest extends TestCase { 7 8 /** 9 * Create an instance of the Matcher so some generic safety-net tests can be run on it. 10 */ 11 protected abstract Matcher<?> createMatcher(); 12 13 public static <T> void assertMatches(Matcher<T> matcher, T arg) { 14 assertMatches("Expected match, but mismatched", matcher, arg); 15 } 16 17 public static <T> void assertMatches(String message, Matcher<T> matcher, T arg) { 18 if (!matcher.matches(arg)) { 19 Assert.fail(message + " because: '" + mismatchDescription(matcher, arg) + "'"); 20 } 21 } 22 23 public static <T> void assertDoesNotMatch(Matcher<? super T> c, T arg) { 24 assertDoesNotMatch("Unexpected match", c, arg); 25 } 26 27 public static <T> void assertDoesNotMatch(String message, Matcher<? super T> c, T arg) { 28 Assert.assertFalse(message, c.matches(arg)); 29 } 30 31 public static void assertDescription(String expected, Matcher<?> matcher) { 32 Description description = new StringDescription(); 33 description.appendDescriptionOf(matcher); 34 Assert.assertEquals("Expected description", expected, description.toString().trim()); 35 } 36 37 public static <T> void assertMismatchDescription(String expected, Matcher<? super T> matcher, T arg) { 38 Assert.assertFalse("Precondition: Matcher should not match item.", matcher.matches(arg)); 39 Assert.assertEquals("Expected mismatch description", expected, mismatchDescription(matcher, arg)); 40 } 41 42 public static void assertNullSafe(Matcher<?> matcher) { 43 try { 44 matcher.matches(null); 45 } 46 catch (Exception e) { 47 Assert.fail("Matcher was not null safe"); 48 } 49 } 50 51 public static void assertUnknownTypeSafe(Matcher<?> matcher) { 52 try { 53 matcher.matches(new UnknownType()); 54 } 55 catch (Exception e) { 56 Assert.fail("Matcher was not unknown type safe"); 57 } 58 } 59 60 public static <T> String mismatchDescription(Matcher<? super T> matcher, T arg) { 61 Description description = new StringDescription(); 62 matcher.describeMismatch(arg, description); 63 return description.toString().trim(); 64 } 65 66 public void testIsNullSafe() { 67 assertNullSafe(createMatcher()); 68 } 69 70 public void testCopesWithUnknownTypes() { 71 assertUnknownTypeSafe(createMatcher()); 72 } 73 74 public static class UnknownType { 75 } 76 77 } 78