170

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

4 Answers 4

297

You can use IsNull.nullValue() method:

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

assertThat(attr.getValue(), is(nullValue()));
4
  • it says method nullValue() is not defined Commented Sep 24, 2013 at 17:02
  • 2
    @user2811419. You need to import IsNull It's a static method in that class. Just do static import, or use IsNull.nullValue().
    – Rohit Jain
    Commented Sep 24, 2013 at 17:03
  • Add import static org.hamcrest.core.IsNull.nullValue; to your class.
    – Rohit Jain
    Commented Sep 24, 2013 at 17:05
  • 5
    In newer versions of Hamcrest the namespace has changed and you need import static org.hamcrest.CoreMatchers.nullValue.
    – ThomasW
    Commented Jan 8, 2016 at 7:18
35

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

4
  • 9
    +1 I generally prefer Hamscrest assertions but this is one case where the Junit assertion is just more readable, IMO.
    – spaaarky21
    Commented Oct 31, 2014 at 18:16
  • 10
    assertThat() give much better logging that many of the other assert* methods. The test-coding standard that I use favors assertThat() over all other assertion methods for this reason.
    – efelton
    Commented Apr 23, 2015 at 15:58
  • 3
    The main advantage when using assertThat vs assertNul is that it is closer to an Englsih spoken phrase, just try to read any of your assertions to check it up.
    – belgoros
    Commented Jul 6, 2016 at 9:28
  • Using an errorCollector is a good reason to use the hamcrest matchers opposed to the assertNull/assertNotNull. Commented Jan 4, 2017 at 17:03
17

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

Use the following (from Hamcrest):

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

In Kotlin is is reserved so use:

assertThat(attr.getValue(), `is`(nullValue()));
2
  • 1
    Is there an alternative where we don't have to escape the is?
    – VIN
    Commented Jul 17, 2020 at 2:13
  • @VIN Probably if you use a fully qualified name instead of a static import?
    – Tazaf
    Commented May 1, 2023 at 14:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.