Search code examples
javahamcrest

Why doesn't this assert work - assertThat(foo, is(not(null)));


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)));

Solution

  • tl;dr

    your assert doesn't work, because you call not(Matcher<T> matcher) with null matcher. Use a shortcut, instead:

        assertThat(foo, notNullValue());
    

    the shortcut:

    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.notNullValue;
        ...
        assertThat(foo, notNullValue());
    

    credits to @eee

    the canonical form:

    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.not;
    import static org.hamcrest.Matchers.nullValue;
        ...
        assertThat(foo, not( nullValue() ));
    

    your (OP) approach:

    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