Collection在jUnit中有效?

是否有一个与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")))); 

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

不直接,不。 我build议使用Hamcrest ,它提供了一套与jUnit(和其他testing框架)很好集成的匹配规则,

看看FEST Fluent断言。 恕我直言,他们比Hamcrest(同样强大,可扩展等)更方便使用,并有stream利的接口,更好的IDE支持。 请参阅https://github.com/alexruiz/fest-assert-2.x/wiki/Using-fest-assertions

Joachim Sauer的解决scheme很好,但是如果你已经有了一系列你想要validation的期望,那么你的结果就不起作用了。 当你的testing中已经有了一个生成或者持续的期望,你可能想要比较一个结果,或者你希望在结果中有多个期望被合并,这可能会出现。 所以,而不是使用匹配器,你可以只使用List::containsAllassertTrue例如:

 @Test public void testMerge() { final List<String> expected1 = ImmutableList.of("a", "b", "c"); final List<String> expected2 = ImmutableList.of("x", "y", "z"); final List<String> result = someMethodToTest(); assertThat(result, hasItems(expected1)); // COMPILE ERROR; DOES NOT WORK assertThat(result, hasItems(expected2)); // COMPILE ERROR; DOES NOT WORK assertTrue(result.containsAll(expected1)); // works~ but has less fancy assertTrue(result.containsAll(expected2)); // works~ but has less fancy }