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

时间:2014-12-15 18:30:58

标签: java junit matcher hamcrest

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

我想我总是可以使用

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

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

3 个答案:

答案 0 :(得分:11)

您可以合并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())));

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

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

答案 1 :(得分:2)

正如我在评论中发布的那样,collection != nullsize != 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()));