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.
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.
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.
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.
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>
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With