【发布时间】:2009-07-06 12:25:27
【问题描述】:
是否有与 NUnit 的 CollectionAssert 平行的 jUnit?
【问题讨论】:
标签: java junit nunit assertion
是否有与 NUnit 的 CollectionAssert 平行的 jUnit?
【问题讨论】:
标签: java junit nunit assertion
使用 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"))));
使用这种方法,您将在断言失败时自动获得对断言的良好描述。
【讨论】:
不直接,不。我建议使用Hamcrest,它提供了一组丰富的匹配规则,可以很好地与jUnit(和其他测试框架)集成
【讨论】:
看看 FEST Fluent Assertions。恕我直言,它们比 Hamcrest 更方便使用(并且同样强大、可扩展等),并且由于流畅的界面而具有更好的 IDE 支持。见https://github.com/alexruiz/fest-assert-2.x/wiki/Using-fest-assertions
【讨论】:
Joachim Sauer 的解决方案很不错,但如果您的结果中已经有一系列想要验证的期望,则该解决方案将不起作用。当您在测试中已经有一个生成的或持续的期望要与结果进行比较时,或者您可能有多个期望合并到结果中时,可能会出现这种情况。因此,您可以只使用List::containsAll 和assertTrue 而不是使用匹配器,例如:
@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
}
【讨论】:
hasItems(expected1.toArray(new String[expected1.size()]))。它会给你更好的失败信息。