是否有一个与NUnit的 CollectionAssert
平行的jUnit?
最佳答案
使用JUnit 4.4,您可以将assertThat()
与Hamcrest代码一起使用(不用担心,它是JUnit附带的,不需要额外的.jar
)来生成复杂的自描述断言,包括对集合进行操作的断言:
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.*;
import static org.hamcrest.CoreMatchers.*;
List<String> l = Arrays.asList("foo", "bar");
assertThat(l, hasItems("foo", "bar"));
assertThat(l, not(hasItem((String) null)));
assertThat(l, not(hasItems("bar", "quux")));
// check if two objects are equal with assertThat()
// the following three lines of code check the same thing.
// the first one is the "traditional" approach,
// the second one is the succinct version and the third one the verbose one
assertEquals(l, Arrays.asList("foo", "bar")));
assertThat(l, is(Arrays.asList("foo", "bar")));
assertThat(l, is(equalTo(Arrays.asList("foo", "bar"))));
使用这种方法,当断言失败时,您将自动获得对断言的良好描述。