这个断言编译但失败,即使我知道 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())));
你的断言不起作用,因为你用
not(Matcher<T> matcher)
匹配器调用 null
。请使用快捷方式:
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() ));
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