尝试使用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)
参考文献
翻译自: https://mkyong.com/unittest/hamcrest-how-to-assertthat-check-null-value/