Main Tutorials

Hamcrest – How to assertThat check null value?

Try to check null value with the Hamcrest assertThat assertion, but no idea how?


	@Test
	public void testApp()
    {
        //ambiguous method call?
        assertThat(null, is(null));
    }

1. Solution

1.1 To check null value, try is(nullValue), remember static import org.hamcrest.CoreMatchers.*



//hello static import, nullValue here
import static org.hamcrest.CoreMatchers.*;
import org.junit.Test;

//...
	@Test
	public void testApp()
    {
        //true, check null
        assertThat(null, is(nullValue()));

        //true, check not null
        assertThat("a", is(notNullValue()));
    }

1.2 Or this equivalent


import static org.hamcrest.CoreMatchers.*;
import org.hamcrest.core.IsNull;
import org.junit.Test;

//...
	@Test
	public void testApp()
    {
        //true, check null
        assertThat(null, is(IsNull.nullValue()));

        //true, check not null
        assertThat("a", is(IsNull.notNullValue()));
    }

The CoreMatchers.nullValue() above (1.1), is a shorthand for IsNull.nullValue, review the following source code :

org.hamcrest.CoreMatchers.java


public static org.hamcrest.Matcher<java.lang.Object> nullValue() {
    return org.hamcrest.core.IsNull.nullValue();
  }

P.S Same to notNullValue()

Note
If you prefer JUnit assertion, try assertNull(null)

References

  1. Hamcrest – IsNull JavaDoc
  2. Hamcrest official site

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
tibi
6 years ago

and how do i test if i have an arrya with only null elements? resutl like this
[
null
]