是否有Hamcrest匹配器检查参数既不是空集合也不是空?
我想我总是可以使用
both(notNullValue()).and(not(hasSize(0))
但我想知道是否有一种更简单的方法,我错过了它。
答案 0 :(得分:11)
您可以合并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()));
答案 1 :(得分:2)
正如我在评论中发布的那样,collection != null
和size != 0
的逻辑等价物是
size > 0
,表示集合不为空。表达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
}
}
答案 2 :(得分:0)
欢迎您使用Matchers:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
assertThat(collection, anyOf(nullValue(), empty()));