13

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)));
epox
  • 9,236
  • 1
  • 55
  • 38
Michael Osofsky
  • 11,429
  • 16
  • 68
  • 113

2 Answers2

12

Empirically, I've found that this works instead:

assertThat(foo, is(not(nullValue())));
Michael Osofsky
  • 11,429
  • 16
  • 68
  • 113
9

tl;dr

your assert doesn't work, because you call not(Matcher<T> matcher) with null matcher. Use a sortcut, 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 to don't confuse not(T value) with not(Matcher<T> matcher). REF: http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html

epox
  • 9,236
  • 1
  • 55
  • 38