How to assertThat something is null with Hamcrest?

JavaAssertHamcrest

Java Problem Overview


How would I assertThat something is null?

for example

 assertThat(attr.getValue(), is(""));

But I get an error saying that I cannot have null in is(null).

Java Solutions


Solution 1 - Java

You can use IsNull.nullValue() method:

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;

assertThat(attr.getValue(), is(nullValue()));

Solution 2 - Java

why not use assertNull(object) / assertNotNull(object) ?

Solution 3 - Java

If you want to hamcrest, you can do

import static org.hamcrest.Matchers.nullValue;

assertThat(attr.getValue(), is(nullValue()));

In Junit you can do

import static junit.framework.Assert.assertNull;
assertNull(object);

Solution 4 - Java

Use the following (from Hamcrest):

assertThat(attr.getValue(), is(nullValue()));

In Kotlin is is reserved so use:

assertThat(attr.getValue(), `is`(nullValue()));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2811419View Question on Stackoverflow
Solution 1 - JavaRohit JainView Answer on Stackoverflow
Solution 2 - JavaChetyaView Answer on Stackoverflow
Solution 3 - JavaSajan ChandranView Answer on Stackoverflow
Solution 4 - JavablackpantherView Answer on Stackoverflow