如何使用Hamcrest断言某个东西是否为空?

168

我如何使用assertThat来判断某个值是否为null

例如:

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

但我遇到了一个错误,说我不能在 is(null) 中使用 null

4个回答

293
你可以使用IsNull.nullValue()方法:
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;

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

方法 nullValue() 未定义。 - user2811419
2
@user2811419。你需要导入IsNull类,它是一个静态方法。只需使用static import或者使用IsNull.nullValue()即可。 - Rohit Jain
import static org.hamcrest.core.IsNull.nullValue; 添加到你的类中。 - Rohit Jain
5
在较新的 Hamcrest 版本中,命名空间已更改,你需要使用 import static org.hamcrest.CoreMatchers.nullValue - ThomasW

35
为什么不使用 assertNull(object) / assertNotNull(object)

9
我通常更喜欢使用Hamscrest断言,但在这种情况下,我认为Junit的断言更易读。+1 - spaaarky21
9
assertThat()方法的日志记录比其他许多assert*方法更好。出于这个原因,我使用的测试编码标准更倾向于使用assertThat()而不是其他所有断言方法。 - efelton
3
使用assertThat相比于使用assertNull的主要优势在于它更接近英语口语,只需尝试读取您的任何断言即可验证。 - belgoros
使用errorCollector是使用hamcrest匹配器而不是assertNull/assertNotNull的好理由。 - Tyler MacMillan

17
如果你想使用hamcrest,可以这样做。
import static org.hamcrest.Matchers.nullValue;

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

Junit 中,您可以执行

import static junit.framework.Assert.assertNull;
assertNull(object);

11

使用以下内容(来自 Hamcrest):

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

在 Kotlin 中,is 是保留的关键字,因此请使用以下语法:
assertThat(attr.getValue(), `is`(nullValue()));

1
有没有其他的替代方案,可以避免我们需要转义 is - VIN
@VIN 如果您使用完全限定名称而不是静态导入,可能会更好? - Tazaf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接