java jUnit中的集合Assert?

v09wglhw  于 2023-02-18  发布在  Java
关注(0)|答案(5)|浏览(203)

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

icomxhvb

icomxhvb1#

使用JUnit 4.4,您可以将assertThat()Hamcrest代码(不用担心,它是随JUnit一起提供的,不需要额外的.jar)一起使用来生成复杂的自描述Assert,包括对集合进行操作的Assert:

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

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

lmvvr0a8

lmvvr0a82#

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

fd3cxomn

fd3cxomn3#

看一看FEST Fluent Assertions。恕我直言,它们比Hamcrest更便于使用(同样强大,可扩展等),并且由于流畅的界面,它们具有更好的IDE支持。

2guxujil

2guxujil4#

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
}
ep6jt1vc

ep6jt1vc5#

使用JUnit 5

Assertions.assertIterableEquals(Iterable<?> expected, Iterable<?> actual)

相关问题