是否有一个Hamcrest匹配器来检查Collection是否为空还是null?

jhy*_*yot 17 java junit hamcrest matcher

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

我想我总是可以使用

both(notNullValue()).and(not(hasSize(0))
Run Code Online (Sandbox Code Playgroud)

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

eee*_*eee 11

您可以组合匹配器IsCollectionWithSizeOrderingComparison匹配器:

@Test
public void test() throws Exception {
    Collection<String> collection = ...;
    assertThat(collection, hasSize(greaterThan(0)));
}
Run Code Online (Sandbox Code Playgroud)
  • collection = null你得到

    java.lang.AssertionError: 
    Expected: a collection with size a value greater than <0>
        but: was null
    
    Run Code Online (Sandbox Code Playgroud)
  • collection = Collections.emptyList()你得到

    java.lang.AssertionError: 
    Expected: a collection with size a value greater than <0>
        but: collection size <0> was equal to <0>
    
    Run Code Online (Sandbox Code Playgroud)
  • 对于collection = Collections.singletonList("Hello world")测试通行证.

编辑:

刚刚注意到以下approch 无法正常工作:

assertThat(collection, is(not(empty())));
Run Code Online (Sandbox Code Playgroud)

我想的越多,如果你想明确地测试null,我会推荐OP写的语句略有改动的版本.

assertThat(collection, both(not(empty())).and(notNullValue()));
Run Code Online (Sandbox Code Playgroud)