How to assertThat something is null with Hamcrest?
Asked Answered
S

4

169

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

Schism answered 24/9, 2013 at 16:58 Comment(0)
C
296

You can use IsNull.nullValue() method:

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

assertThat(attr.getValue(), is(nullValue()));
Cantor answered 24/9, 2013 at 17:0 Comment(4)
it says method nullValue() is not definedSchism
@user2811419. You need to import IsNull It's a static method in that class. Just do static import, or use IsNull.nullValue().Cantor
Add import static org.hamcrest.core.IsNull.nullValue; to your class.Cantor
In newer versions of Hamcrest the namespace has changed and you need import static org.hamcrest.CoreMatchers.nullValue.Krys
R
35

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

Renatarenate answered 24/9, 2013 at 17:0 Comment(4)
+1 I generally prefer Hamscrest assertions but this is one case where the Junit assertion is just more readable, IMO.Saturable
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.Ornithic
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.Cissoid
Using an errorCollector is a good reason to use the hamcrest matchers opposed to the assertNull/assertNotNull.Lyso
H
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);
Hauteloire answered 24/9, 2013 at 17:4 Comment(0)
I
12

Use the following (from Hamcrest):

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

In Kotlin is is reserved so use:

assertThat(attr.getValue(), `is`(nullValue()));
Infringement answered 24/9, 2013 at 17:2 Comment(2)
Is there an alternative where we don't have to escape the is?Sherlock
@Sherlock Probably if you use a fully qualified name instead of a static import?Definitely

© 2022 - 2024 — McMap. All rights reserved.