Mik*_*der 7 java junit unit-testing hamcrest assertions
我想验证集合是否包含至少一个非null元素.我试过is(not(empty())),但是这通过了下面的测试.
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())));
}
}
Run Code Online (Sandbox Code Playgroud)
有一种优雅/简单的方法吗?
不起作用的事情
@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)
Run Code Online (Sandbox Code Playgroud)
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
...
assertThat(collection, hasItem(notNullValue(Integer.class)));
Run Code Online (Sandbox Code Playgroud)
不幸的是,有一个在Java 1.6的错误,这意味着你可能必须将其分割到所描述的2号线在这里,如果你使用的是1.6:
Matcher<Iterable<? super String>> matcher = hasItem(notNullValue(Integer.class));
assertThat(collection, matcher);
Run Code Online (Sandbox Code Playgroud)
编辑这是您要求的FEST Assert示例:
import static org.fest.assertions.api.Assertions.assertThat;
...
assertThat(collection).doesNotContainNull();
Run Code Online (Sandbox Code Playgroud)
FEST只需要一次静态导入,因此您可以获得完整的IDE自动完成功能.