是否有 Hamcrest 匹配器来检查集合是否既不为空也不为空?

2022-09-02 13:40:31

是否有 Hamcrest 匹配器可以检查参数是否既不是空集合也不是 null?

我想我总是可以使用

both(notNullValue()).and(not(hasSize(0))

但我想知道是否有更简单的方法,我错过了它。


答案 1

您可以将 IsCollectionWithSizeOrderIngComparison 匹配器组合在一起:

@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())));

我越想越建议OP编写的语句的稍微改变版本,如果你想明确测试null。

assertThat(collection, both(not(empty())).and(notNullValue()));

答案 2

正如我在评论中发布的,和 的逻辑等价物是 ,这意味着集合不为空。一种更简单的表达方法是。下面是一个工作代码示例。collection != nullsize != 0size > 0size > 0there 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 
    }
}

推荐