[英]Is there a Hamcrest matcher to check that a Collection is neither empty nor null?
是否有Hamcrest匹配器檢查參數既不是空集合也不是空?
我想我總是可以使用
both(notNullValue()).and(not(hasSize(0))
但我想知道是否有更簡單的方法,我錯過了它。
您可以組合IsCollectionWithSize
和OrderingComparison
匹配器:
@Test
public void test() throws Exception {
Collection<String> collection = ...;
assertThat(collection, hasSize(greaterThan(0)));
}
對於collection = null
你得到
java.lang.AssertionError: Expected: a collection with size a value greater than <0> but: was null
對於collection = Collections.emptyList()
你得到
java.lang.AssertionError: Expected: a collection with size a value greater than <0> but: collection size <0> was equal to <0>
collection = Collections.singletonList("Hello world")
,測試通過。 編輯:
剛剛注意到以下approch 無法正常工作:
assertThat(collection, is(not(empty())));
我想的越多,如果你想明確地測試null,我會推薦OP寫的語句略有改動的版本。
assertThat(collection, both(not(empty())).and(notNullValue()));
正如我在評論中發布的那樣, collection != null
和size != 0
的邏輯等價物是size > 0
,這意味着集合不為null。 表示size > 0
更簡單方法是there is an (arbitrary) element X in collection
下面是一個工作代碼示例。
import static org.hamcrest.core.IsCollectionContaining.hasItem;
import static org.hamcrest.CoreMatchers.anything;
public class Main {
public static void main(String[] args) {
boolean result = hasItem(anything()).matches(null);
System.out.println(result); // false for null
result = hasItem(anything()).matches(Arrays.asList());
System.out.println(result); // false for empty
result = hasItem(anything()).matches(Arrays.asList(1, 2));
System.out.println(result); // true for (non-null and) non-empty
}
}
歡迎您使用Matchers:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
assertThat(collection, anyOf(nullValue(), empty()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.