166

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

WW.
  • 23,793
  • 13
  • 94
  • 121
user2811419
  • 1,923
  • 2
  • 14
  • 15

4 Answers4

291

You can use IsNull.nullValue() method:

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

assertThat(attr.getValue(), is(nullValue()));
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
35

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

blackpanther
  • 10,998
  • 11
  • 48
  • 78
Chetya
  • 1,267
  • 1
  • 17
  • 31
  • 9
    +1 I generally prefer Hamscrest assertions but this is one case where the Junit assertion is just more readable, IMO. – spaaarky21 Oct 31 '14 at 18:16
  • 9
    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 Apr 23 '15 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 Jul 06 '16 at 09:28
  • Using an errorCollector is a good reason to use the hamcrest matchers opposed to the assertNull/assertNotNull. – Tyler MacMillan Jan 04 '17 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);
Sajan Chandran
  • 11,287
  • 3
  • 29
  • 38
11

Use the following (from Hamcrest):

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

In Kotlin is is reserved so use:

assertThat(attr.getValue(), `is`(nullValue()));
Idrizi.A
  • 9,819
  • 11
  • 47
  • 88
blackpanther
  • 10,998
  • 11
  • 48
  • 78