是否有与 NUnit 平行的 jUnit CollectionAssert
?
问问题
50787 次
4 回答
127
使用 JUnit 4.4,您可以与HamcrestassertThat()
代码一起使用(不用担心,它是 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"))));
使用这种方法,您将在断言失败时自动获得断言的良好描述。
于 2009-07-06T12:32:52.967 回答
4
不直接,不。我建议使用Hamcrest,它提供了一组丰富的匹配规则,可以很好地与 jUnit(和其他测试框架)集成
于 2009-07-06T12:32:09.127 回答
2
看看 FEST Fluent 断言。恕我直言,它们比 Hamcrest 更方便使用(并且同样强大、可扩展等),并且由于流畅的界面而具有更好的 IDE 支持。见https://github.com/alexruiz/fest-assert-2.x/wiki/Using-fest-assertions
于 2012-09-19T18:50:45.853 回答
2
Joachim Sauer 的解决方案很好,但如果您已经有一系列希望验证结果中的期望,则该解决方案不起作用。当您在测试中已经有一个生成的或持续的期望要与结果进行比较时,或者您可能有多个期望合并到结果中时,可能会出现这种情况。因此,您可以使用List::containsAll
and而不是使用匹配器,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
}
于 2016-10-18T16:25:12.023 回答