Is there a Hamcrest matcher to check that a Collection is neither empty nor null?
You are welcome to use Matchers:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
assertThat(collection, anyOf(nullValue(), empty()));
As I posted in the comments, the logical equivalent of collection != null
and size != 0
is
size > 0
, that implies the collection is not null. A simpler way to express size > 0
is there is an (arbitrary) element X in collection
. Below a working code example.
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
}
}
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 getjava.lang.AssertionError: Expected: a collection with size a value greater than <0> but: was null
For
collection = Collections.emptyList()
you getjava.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()));