Search code examples
javaunit-testingjunitassertionshamcrest

Assert that collection "Contains at least one non-null element"


I want to verify that a collection contains at least one non-null element. I have tried is(not(empty())), however this passes in the test below.

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collection;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.not;

public class SandBoxTest {
    @Test
    public void shouldTestThis() {
        Collection<Integer> collection = new ArrayList<Integer>();
        collection.add(null);

        assertThat(collection, is(not(empty())));
    }
}

Is there an elegant/simple way to do this?

Things That Don't Work

@Test
public void should(){
    Collection<String> collection = new ArrayList();
    collection.add("gfas");
    collection.add("asda");
    assertThat(collection, contains(notNullValue()));
}

java.lang.AssertionError: 
Expected: iterable containing [not null]
     but: Not matched: "asda"
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)

Solution

  • import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.*;
    
    ...
        
    assertThat(collection, hasItem(notNullValue(Integer.class)));
    

    Unfortunately, there is a bug in Java 1.6 that means you might have to split it onto 2 lines as described here if you are using 1.6:

    Matcher<Iterable<? super String>> matcher = hasItem(notNullValue(Integer.class));
    assertThat(collection, matcher);
    

    EDIT Here is the FEST Assert example you asked for:

    import static org.fest.assertions.api.Assertions.assertThat;
    ...
    assertThat(collection).doesNotContainNull();
    

    FEST requires only a single static import so you get full IDE auto completion.