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

Java 是否有Hamcrest匹配器来检查集合既不是空的也不是空的?,java,junit,matcher,hamcrest,Java,Junit,Matcher,Hamcrest,是否有一个Hamcrest匹配器来检查参数既不是空集合也不是null 我想我可以一直用它 both(notNullValue()).and(not(hasSize(0)) 但是我想知道是否有一种更简单的方法,我错过了。正如我在评论中发布的那样,这是集合的逻辑等价物!=空值和大小!=0 size>0,表示集合不为空。表示size>0的一种简单方法是集合中有一个(任意)元素X。下面是一个工作代码示例 import static org.hamcrest.core.IsCollectionConta

是否有一个Hamcrest匹配器来检查参数既不是空集合也不是null

我想我可以一直用它

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

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

正如我在评论中发布的那样,这是
集合的逻辑等价物!=空值
大小!=0
size>0
,表示集合不为空。表示
size>0
的一种简单方法是
集合中有一个(任意)元素X
。下面是一个工作代码示例

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 
    }
}
您可以将和匹配器结合使用:

  • 对于
    collection=Collections.emptyList()

    java.lang.AssertionError: 
    Expected: a collection with size a value greater than <0>
        but: was null
    
    java.lang.AssertionError: 
    Expected: a collection with size a value greater than <0>
        but: collection size <0> was equal to <0>
    
    如果您想显式测试null,我越是考虑它,就越建议对OP编写的语句进行稍微修改

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

    欢迎您使用Matchers:

    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.anyOf;
    
    assertThat(collection, anyOf(nullValue(), empty()));
    

    我觉得这很简单。此外,您的测试尽可能清晰地表达其意图,并且代码可读性很强,这一点很重要。我真的不知道hamcrest,但从逻辑上讲,如果API支持此类调用,您可以检查
    大小>=0
    。此问题的标题与此问题的正文相反。回答问题的标题:
    assertThat(元数据,要么是(empty())。要么是(nullValue()))与您的问题不完全匹配,但您可以
    assertTrue(CollectionUtils.isNotEmpty(collectioin))
    CollectionUtils
    是一个Apache Commons Lang类。我接受了你的答案,因为我认为这里显示的两种方法,
    hasSize(大于(0))
    都是(not(empty())。和(notNullValue())
    都是一个好方法。我得到
    1期望失败的任何原因。JSON路径映像不匹配。预期:(空集合或null)实际:当我尝试用代码检查空集合或null时:
    myResponse.body(myArrayAttr,或者(empty())。或者(nullValue())
    
    assertThat(collection, both(not(empty())).and(notNullValue()));
    
    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.anyOf;
    
    assertThat(collection, anyOf(nullValue(), empty()));