这个断言编译但是失败,即使我知道foo不是null的事实:
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)));
答案 0 :(得分:2)
根据经验,我发现这是有效的:
assertThat(foo, is(not(nullValue())));
答案 1 :(得分:1)
快捷方式:
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() ));
上面是规范形式
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
...
assertThat(foo, not( (Foo)null ));
在最新示例中,必须进行类型转换,以免将not(T value)
与not(Matcher<T> matcher)
混淆。
REF:http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html