Joa*_*uer 123

使用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"))));
Run Code Online (Sandbox Code Playgroud)

使用这种方法,您将在失败时自动获得断言的良好描述.

  • 嗯,丑陋.在NUnit中,CollectionAssert.AreEqual(Collection expected,Collection actual); (3认同)