Altair7852
Altair7852

Reputation: 1418

Standard Hamcrest matcher to check if collection is empty or null?

Is there a shorter version of the following assert statement using standard Hamcrest matchers?

Collection<Element> collection = ...

assertThat(collection, is(anyOf(nullValue(Collection.class), 
     emptyCollectionOf(Element.class))));

I realize there is a way to create a custom matcher, was hoping that maybe there is already something in place that addresses this without any additional code change.

Upvotes: 9

Views: 6200

Answers (4)

hovanessyan
hovanessyan

Reputation: 31433

One way to achieve this would be to create a custom Hamcrest matcher, which combines already available matches (like IsNull.nullValue() and IsEmptyCollection.empty()).

But generally speaking an assert should assert for one thing only. My opinion is that it's not a huge pain to have two matchers in succession and it's more readable later.

Also there's another preferred pattern - when returning a collection, prefer returning empty collection instead of null. The idea is to avoid unnecessary null checks.

Upvotes: 2

jihor
jihor

Reputation: 2599

There is no out-of-the-box solution, and worse, either() can't be used due to this bug. So the shortest way is this:

assertThat(collection, anyOf(nullValue(), empty()));

Upvotes: 14

MikeFHay
MikeFHay

Reputation: 8983

Consider a simple imperative solution using Assert.fail.

if (collection != null && !collection.isEmpty()) {
    fail(collection.toString());
}

Upvotes: 0

daniu
daniu

Reputation: 14999

The only way I can think of is to write your own Matcher

class EmptyOrNull extends BaseMatcher<Collection> {
    public boolean matches(Object o) {
        boolean result = o == null;
        if (o instanceof Collection) {
            result = ((Collection) o).isEmpty();
        }
        return result;
    }
    public String describeMismatch(Object item, Description description) {
        return "not null or empty!";
    }
    public static Matcher<Collection> emptyOrNull() { return new EmptyOrNull(); }
}

and then you can use the shorter version.

assertThat(collection, emptyOrNull());

Upvotes: 1

Related Questions