jUnit中的CollectionAssert?

时间:2009-07-06 12:25:28

标签: java junit nunit assertion

是否有一个与NUnit的CollectionAssert平行的jUnit?

4 个答案:

答案 0 :(得分:117)

使用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"))));

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

答案 1 :(得分:4)

不直接,不。我建议使用Hamcrest,它提供了一组丰富的匹配规则,可以很好地与jUnit(和其他测试框架)集成。

答案 2 :(得分:2)

看看FEST Fluent Assertions。恕我直言,它们比Hamcrest更方便(同样强大,可扩展等),并且由于流畅的界面,它具有更好的IDE支持。见https://github.com/alexruiz/fest-assert-2.x/wiki/Using-fest-assertions

答案 3 :(得分:1)

Joachim Sauer的解决方案很不错,但是如果您已经有一系列期望要验证的结果,那么它就不起作用了。当您在测试中已经有一个想要比较结果的生成或持续期望时,或者您可能希望在结果中合并多个期望时,可能会出现这种情况。因此,您可以使用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
}