Java 如何用Hamcrest断言某些内容为空?
我如何断言某个东西是Java 如何用Hamcrest断言某些内容为空?,java,assert,hamcrest,Java,Assert,Hamcrest,我如何断言某个东西是空的 比如说 assertThat(attr.getValue(), is("")); 但是我得到一个错误,说我不能在is(null)中使用null为什么不使用assertNull(object)/assertNotNull(object)?您可以使用以下方法: 使用以下内容(来自Hamcrest): 在Kotlin中,是是保留的,因此使用: assertThat(attr.getValue(), `is`(nullValue())); 如果您想hamcrest,您可以
空的
比如说
assertThat(attr.getValue(), is(""));
但是我得到一个错误,说我不能在
is(null)
中使用null
为什么不使用assertNull(object)
/assertNotNull(object)
?您可以使用以下方法:
使用以下内容(来自Hamcrest):
在Kotlin中,是
是保留的,因此使用:
assertThat(attr.getValue(), `is`(nullValue()));
如果您想
hamcrest
,您可以这样做
import static org.hamcrest.Matchers.nullValue;
assertThat(attr.getValue(), is(nullValue()));
import static junit.framework.Assert.assertNull;
assertNull(object);
在Junit中,您可以执行以下操作
import static org.hamcrest.Matchers.nullValue;
assertThat(attr.getValue(), is(nullValue()));
import static junit.framework.Assert.assertNull;
assertNull(object);
它说方法nullValue()不是defined@user2811419. 您需要导入
IsNull
它是该类中的静态方法。只需执行静态导入
,或使用IsNull.nullValue()
。添加导入static org.hamcrest.core.IsNull.nullValue在更新版本的Hamcrest中,名称空间已经更改,您需要导入static org.Hamcrest.CoreMatchers.nullValue
+1我通常更喜欢Hamscrest断言,但在这种情况下Junit断言更具可读性,IMO.assertThat()比其他许多assert*方法提供更好的日志记录。因此,我使用的测试编码标准优先于所有其他断言方法。使用assertThat vs assertNul的主要优点是它更接近英语口语短语,只要试着阅读您的任何断言来检查它。使用errorCollector是使用hamcrest matchers而不是assertNull/assertNotNull的一个很好的理由。是否有一种替代方法,我们不必逃避is
?