我該如何assertThat
東西是null
?如何斷定Hamcrest的內容爲空?
例如
assertThat(attr.getValue(), is(""));
但我得到一個錯誤說我不能有null
在is(null)
。
我該如何assertThat
東西是null
?如何斷定Hamcrest的內容爲空?
例如
assertThat(attr.getValue(), is(""));
但我得到一個錯誤說我不能有null
在is(null)
。
您可以使用方法:
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
assertThat(attr.getValue(), is(nullValue()));
爲什麼不使用assertNull(object)
/assertNotNull(object)
?
+1我通常更喜歡Hamscrest聲明,但這是Junit聲明更具可讀性的一種情況,IMO。 – spaaarky21
assertThat()給出了許多其他斷言*方法更好的日誌記錄。由於這個原因,我使用的測試編碼標準主張()所有其他斷言方法。 – efelton
使用assertThat vs assertNul的主要優勢在於它更接近Englsih口語短語,只是嘗試閱讀您的任何斷言來檢查它。 – belgoros
使用以下(從Hamcrest):
assertThat(attr.getValue(), is(nullValue()));
如果你想hamcrest
,你可以做
import static org.hamcrest.Matchers.nullValue;
assertThat(attr.getValue(), is(nullValue()));
在Junit
你可以做
import static junit.framework.Assert.assertNull;
assertNull(object);
它說方法nullValue()沒有定義 – user2811419
@ user2811419。您需要導入'IsNull'這是該類中的靜態方法。只要執行'static import',或者使用'IsNull.nullValue()'。 –
將'import static org.hamcrest.core.IsNull.nullValue;'添加到您的類中。 –