This assertion compiles but fails even though I know for a fact that foo is not null:
import static org.hamcrest.Matchers.is; // see http://stackoverflow.com/a/27256498/2848676
import static org.hamcrest.Matchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
...
assertThat(foo, is(not(null)));
your assert doesn't work, because you call not(Matcher<T> matcher)
with null
matcher. Use a shortcut, instead:
assertThat(foo, notNullValue());
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
...
assertThat(foo, notNullValue());
credits to @eee
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
...
assertThat(foo, not( nullValue() ));
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
...
assertThat(foo, not( (Foo)null ));
The type casting is required here, in order not to confuse not(T value)
with not(Matcher<T> matcher)
.
REF: http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html