Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hamcrest

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)));
like image 279
Michael Osofsky Avatar asked Dec 16 '14 04:12

Michael Osofsky


People also ask

What is assertThat in JUnit?

The assertThat is one of the JUnit methods from the Assert object that can be used to check if a specific value match to an expected one. It primarily accepts 2 parameters. First one if the actual value and the second is a matcher object.

Why assertThat is deprecated?

assertThat method is deprecated. Its sole purpose is to forward the call to the MatcherAssert. assertThat method defined in Hamcrest 1.3. Therefore, it is recommended to directly use the equivalent assertion defined in the third party Hamcrest library.

What does assert not null do in Java?

Assert. assertNotNull() methods checks that the object is null or not. If it is null then it throws an AssertionError.

How do you assert null in JUnit?

Assert class in case of JUnit 4 or JUnit 3 to assert using assertNull method. Assertions. assertNull() checks that object is null. In case, object is not null, it will through AssertError.


2 Answers

Empirically, I've found that this works instead:

assertThat(foo, is(not(nullValue())));
like image 196
Michael Osofsky Avatar answered Oct 01 '22 08:10

Michael Osofsky


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

like image 21
epox Avatar answered Oct 01 '22 09:10

epox