Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 479
jhyot Avatar asked Dec 15 '14 18:12

jhyot


People also ask

What is a Hamcrest matcher?

Hamcrest is a framework that assists writing software tests in the Java programming language. It supports creating customized assertion matchers ('Hamcrest' is an anagram of 'matchers'), allowing match rules to be defined declaratively. These matchers have uses in unit testing frameworks such as JUnit and jMock.

Why are there Hamcrest matchers?

Purpose of the Hamcrest matcher framework. Hamcrest is a widely used framework for unit testing in the Java world. Hamcrest target is to make your tests easier to write and read. For this, it provides additional matcher classes which can be used in test for example written with JUnit.

What is matchers in JUnit?

Matchers along with assertThat were introduced in JUnit 4.4. assertThat provides a way to write clean highly readable assertions, taking advantage of matchers. These matchers are provided by a library called Hamcrest.


1 Answers

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()));
like image 122
eee Avatar answered Sep 20 '22 04:09

eee