如何使用Hamcrest声明某些东西是空的?

use*_*419 134 java assert hamcrest

我怎么assertThatnull

例如

 assertThat(attr.getValue(), is(""));
Run Code Online (Sandbox Code Playgroud)

但我得到一个错误,说我不能null进去is(null).

Roh*_*ain 241

你可以使用IsNull.nullValue()方法:

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;

assertThat(attr.getValue(), is(nullValue()));
Run Code Online (Sandbox Code Playgroud)

  • 在较新版本的Hamcrest中,命名空间已经改变,你需要`import static org.hamcrest.CoreMatchers.nullValue`. (4认同)
  • @ user2811419.你需要导入`IsNull`它是该类中的静态方法.只需执行`static import`,或使用`IsNull.nullValue()`. (2认同)

Che*_*tya 28

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

  • +1我通常更喜欢Hamscrest断言,但这是Junit断言更具可读性的一种情况,IMO. (7认同)
  • assertThat()提供了许多其他断言*方法的更好的日志记录.由于这个原因,我使用的测试编码标准倾向于断言所有其他断言方法的断言(). (7认同)
  • 使用assertThat与assertNul的主要优点是,它更接近于Englsih口头短语,只需尝试阅读您的任何断言进行检查即可。 (2认同)

Saj*_*ran 14

如果你愿意hamcrest,你可以做到

import static org.hamcrest.Matchers.nullValue;

assertThat(attr.getValue(), is(nullValue()));
Run Code Online (Sandbox Code Playgroud)

Junit你能做到的

import static junit.framework.Assert.assertNull;
assertNull(object);
Run Code Online (Sandbox Code Playgroud)


bla*_*her 9

使用以下(来自Hamcrest):

assertThat(attr.getValue(), is(nullValue()));
Run Code Online (Sandbox Code Playgroud)