I want to verify that the collection contains at least one nonzero element. I 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 / easy 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)
java unit-testing junit assertions hamcrest
Mike rylander
source share