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

2

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 https://mcmap.net/q/575499/-is-org-junit-assert-assertthat-better-than-org-hamcrest-matcherassert-assertthat
import static org.hamcrest.Matchers.not;
import static org.hamcrest.MatcherAssert.assertThat;

...

assertThat(foo, is(not(null)));
Spadiceous answered 16/12, 2014 at 4:4 Comment(0)
S
11

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

Seaway answered 10/8, 2019 at 15:41 Comment(0)
S
12

Empirically, I've found that this works instead:

assertThat(foo, is(not(nullValue())));
Spadiceous answered 16/12, 2014 at 4:4 Comment(1)
There is even a own method for this: Matchers.notNullValue().Prefatory
S
11

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

Seaway answered 10/8, 2019 at 15:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.