繁体   English   中英

为什么这个断言不起作用 - assertThat(foo, is(not(null)));

[英]Why doesn't this assert work - assertThat(foo, is(not(null)));

即使我知道 foo 不为空这一事实,该断言也能编译但失败:

import static org.hamcrest.Matchers.is;  // see http://stackoverflow.com/a/27256498/2848676
import static org.hamcrest.Matchers.not;
import static org.hamcrest.MatcherAssert.assertThat;

...

assertThat(foo, is(not(null)));

根据经验,我发现这可以代替:

assertThat(foo, is(not(nullValue())));

tl;博士

你的断言不起作用,因为你用null匹配器调用not(Matcher<T> matcher) 改用 sortcut:

    assertThat(foo, notNullValue());

捷径:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
    ...
    assertThat(foo, notNullValue());

归功于@eee

规范形式:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
    ...
    assertThat(foo, not( nullValue() ));

您的(OP)方法:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
    ...
    assertThat(foo, not( (Foo)null ));

这里需要类型转换,以免将not(T value)not(Matcher<T> matcher)混淆。 参考: http : //hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM