[英]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())));
你的斷言不起作用,因為你用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() ));
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.