欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hamcrest –如何断言检查空值?

程序员文章站 2024-03-15 08:34:47
...

尝试使用Hamcrest assertThat断言检查空值,但不知道如何做?

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

1.解决方案

1.1要检查空值,请尝试is(nullValue) ,请记住静态导入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或等效

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()));
    }

上面(1.1)的CoreMatchers.nullValue()IsNull.nullValue的简写,请查看以下源代码:

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

PS与notNullValue()相同

注意
如果您喜欢JUnit声明,请尝试assertNull(null)

参考文献

  1. Hamcrest – IsNull JavaDoc
  2. Hamcrest官方网站

From: https://mkyong.com/unittest/hamcrest-how-to-assertthat-check-null-value/