1 package org.hamcrest.core; 2 3 import org.hamcrest.BaseMatcher; 4 import org.hamcrest.Description; 5 import org.hamcrest.Matcher; 6 7 import static org.hamcrest.core.IsEqual.equalTo; 8 import static org.hamcrest.core.IsInstanceOf.instanceOf; 9 10 /** 11 * Decorates another Matcher, retaining the behaviour but allowing tests 12 * to be slightly more expressive. 13 * 14 * For example: assertThat(cheese, equalTo(smelly)) 15 * vs. assertThat(cheese, is(equalTo(smelly))) 16 */ 17 public class Is<T> extends BaseMatcher<T> { 18 private final Matcher<T> matcher; 19 Is(Matcher<T> matcher)20 public Is(Matcher<T> matcher) { 21 this.matcher = matcher; 22 } 23 24 @Override matches(Object arg)25 public boolean matches(Object arg) { 26 return matcher.matches(arg); 27 } 28 29 @Override describeTo(Description description)30 public void describeTo(Description description) { 31 description.appendText("is ").appendDescriptionOf(matcher); 32 } 33 34 @Override describeMismatch(Object item, Description mismatchDescription)35 public void describeMismatch(Object item, Description mismatchDescription) { 36 matcher.describeMismatch(item, mismatchDescription); 37 } 38 39 /** 40 * Decorates another Matcher, retaining its behaviour, but allowing tests 41 * to be slightly more expressive. 42 * For example: 43 * <pre>assertThat(cheese, is(equalTo(smelly)))</pre> 44 * instead of: 45 * <pre>assertThat(cheese, equalTo(smelly))</pre> 46 * 47 */ is(Matcher<T> matcher)48 public static <T> Matcher<T> is(Matcher<T> matcher) { 49 return new Is<T>(matcher); 50 } 51 52 /** 53 * A shortcut to the frequently used <code>is(equalTo(x))</code>. 54 * For example: 55 * <pre>assertThat(cheese, is(smelly))</pre> 56 * instead of: 57 * <pre>assertThat(cheese, is(equalTo(smelly)))</pre> 58 * 59 */ is(T value)60 public static <T> Matcher<T> is(T value) { 61 return is(equalTo(value)); 62 } 63 64 /** 65 * A shortcut to the frequently used <code>is(instanceOf(SomeClass.class))</code>. 66 * For example: 67 * <pre>assertThat(cheese, isA(Cheddar.class))</pre> 68 * instead of: 69 * <pre>assertThat(cheese, is(instanceOf(Cheddar.class)))</pre> 70 * 71 */ isA(Class<T> type)72 public static <T> Matcher<T> isA(Class<T> type) { 73 final Matcher<T> typeMatcher = instanceOf(type); 74 return is(typeMatcher); 75 } 76 } 77