001 package org.hamcrest.core; 002 003 import org.hamcrest.BaseMatcher; 004 import org.hamcrest.Description; 005 import org.hamcrest.Factory; 006 import org.hamcrest.Matcher; 007 008 import static org.hamcrest.core.IsEqual.equalTo; 009 import static org.hamcrest.core.IsInstanceOf.instanceOf; 010 011 /** 012 * Decorates another Matcher, retaining the behaviour but allowing tests 013 * to be slightly more expressive. 014 * 015 * For example: assertThat(cheese, equalTo(smelly)) 016 * vs. assertThat(cheese, is(equalTo(smelly))) 017 */ 018 public class Is<T> extends BaseMatcher<T> { 019 private final Matcher<T> matcher; 020 021 public Is(Matcher<T> matcher) { 022 this.matcher = matcher; 023 } 024 025 @Override 026 public boolean matches(Object arg) { 027 return matcher.matches(arg); 028 } 029 030 @Override 031 public void describeTo(Description description) { 032 description.appendText("is ").appendDescriptionOf(matcher); 033 } 034 035 @Override 036 public void describeMismatch(Object item, Description mismatchDescription) { 037 matcher.describeMismatch(item, mismatchDescription); 038 } 039 040 /** 041 * Decorates another Matcher, retaining its behaviour, but allowing tests 042 * to be slightly more expressive. 043 * <p/> 044 * For example: 045 * <pre>assertThat(cheese, is(equalTo(smelly)))</pre> 046 * instead of: 047 * <pre>assertThat(cheese, equalTo(smelly))</pre> 048 * 049 */ 050 @Factory 051 public static <T> Matcher<T> is(Matcher<T> matcher) { 052 return new Is<T>(matcher); 053 } 054 055 /** 056 * A shortcut to the frequently used <code>is(equalTo(x))</code>. 057 * <p/> 058 * For example: 059 * <pre>assertThat(cheese, is(smelly))</pre> 060 * instead of: 061 * <pre>assertThat(cheese, is(equalTo(smelly)))</pre> 062 * 063 */ 064 @Factory 065 public static <T> Matcher<T> is(T value) { 066 return is(equalTo(value)); 067 } 068 069 /** 070 * A shortcut to the frequently used <code>is(instanceOf(SomeClass.class))</code>. 071 * <p/> 072 * For example: 073 * <pre>assertThat(cheese, is(Cheddar.class))</pre> 074 * instead of: 075 * <pre>assertThat(cheese, is(instanceOf(Cheddar.class)))</pre> 076 * 077 * @deprecated use isA(Class<T> type) instead. 078 */ 079 @Factory 080 @Deprecated 081 public static <T> Matcher<T> is(Class<T> type) { 082 final Matcher<T> typeMatcher = instanceOf(type); 083 return is(typeMatcher); 084 } 085 086 /** 087 * A shortcut to the frequently used <code>is(instanceOf(SomeClass.class))</code>. 088 * <p/> 089 * For example: 090 * <pre>assertThat(cheese, isA(Cheddar.class))</pre> 091 * instead of: 092 * <pre>assertThat(cheese, is(instanceOf(Cheddar.class)))</pre> 093 * 094 */ 095 @Factory 096 public static <T> Matcher<T> isA(Class<T> type) { 097 final Matcher<T> typeMatcher = instanceOf(type); 098 return is(typeMatcher); 099 } 100 }