簡體   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