[英]Why doesn't this assert work - assertThat(foo, is(not(null)));
This assertion compiles but fails even though I know for a fact that 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())));
your assert doesn't work, because you call not(Matcher<T> matcher)
with null
matcher.你的断言不起作用,因为你用null
匹配器调用not(Matcher<T> matcher)
。 Use a sortcut, instead:改用 sortcut:
assertThat(foo, notNullValue());
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
...
assertThat(foo, notNullValue());
credits to @eee归功于@eee
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
...
assertThat(foo, not( nullValue() ));
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
...
assertThat(foo, not( (Foo)null ));
The type casting is required here, in order to don't confuse not(T value)
with not(Matcher<T> matcher)
.这里需要类型转换,以免将not(T value)
与not(Matcher<T> matcher)
混淆。 REF: http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html参考: http : //hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.