Checking that a List is not empty in Hamcrest Checking that a List is not empty in Hamcrest java java

Checking that a List is not empty in Hamcrest


Well there's always

assertThat(list.isEmpty(), is(false));

... but I'm guessing that's not quite what you meant :)

Alternatively:

assertThat((Collection)list, is(not(empty())));

empty() is a static in the Matchers class. Note the need to cast the list to Collection, thanks to Hamcrest 1.2's wonky generics.

The following imports can be used with hamcrest 1.3

import static org.hamcrest.Matchers.empty;import static org.hamcrest.core.Is.is;import static org.hamcrest.core.IsNot.*;


This is fixed in Hamcrest 1.3. The below code compiles and does not generate any warnings:

// givenList<String> list = new ArrayList<String>();// thenassertThat(list, is(not(empty())));

But if you have to use older version - instead of bugged empty() you could use:

hasSize(greaterThan(0))
(import static org.hamcrest.number.OrderingComparison.greaterThan; or
import static org.hamcrest.Matchers.greaterThan;)

Example:

// givenList<String> list = new ArrayList<String>();// thenassertThat(list, hasSize(greaterThan(0)));

The most important thing about above solutions is that it does not generate any warnings.The second solution is even more useful if you would like to estimate minimum result size.


If you're after readable fail messages, you can do without hamcrest by using the usual assertEquals with an empty list:

assertEquals(new ArrayList<>(0), yourList);

E.g. if you run

assertEquals(new ArrayList<>(0), Arrays.asList("foo", "bar");

you get

java.lang.AssertionErrorExpected :[]Actual   :[foo, bar]