Search code examples
javajunitmatcherhamcrest

Is there a Hamcrest matcher to check that a Collection is neither empty nor null?


Is there a Hamcrest matcher which checks that the argument is neither an empty Collection nor null?

I guess I could always use

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

but I was wondering whether there is a simpler way and I missed it.


Solution

  • You can combine the IsCollectionWithSize and the OrderingComparison matcher:

    @Test
    public void test() throws Exception {
        Collection<String> collection = ...;
        assertThat(collection, hasSize(greaterThan(0)));
    }
    
    • For collection = null you get

      java.lang.AssertionError: 
      Expected: a collection with size a value greater than <0>
          but: was null
      
    • For collection = Collections.emptyList() you get

      java.lang.AssertionError: 
      Expected: a collection with size a value greater than <0>
          but: collection size <0> was equal to <0>
      
    • For collection = Collections.singletonList("Hello world") the test passes.

    Edit:

    Just noticed that the following approch is not working:

    assertThat(collection, is(not(empty())));
    

    The more i think about it the more i would recommend a slightly altered version of the statement written by the OP if you want to test explicitly for null.

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