在jUnit中有CollectionAssert吗?


Answers:


125

使用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
哦,我还没意识到hamcrest进入了junit发行版。纳特!
skaffman's

如果我想断言l是由项目(“ foo”,“ bar”)组成的,但是不存在其他项目-是否有一些简单的语法?
ripper234

使用上面的代码片段并抛出一个额外的assertTrue(l.size()== 2)
aberrant80

4
嗯,丑陋。在NUnit中,这是CollectionAssert.AreEqual(期望收集,实际收集);
ripper234 2009年

1
Google找到了我正在寻找的另一个Stackoverflow答案!
Mykola Golubyev 09年

4

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


由于某种原因,它不能编译(请参见stackoverflow.com/questions/1092981/hamcrests-hasitems):ArrayList <Integer> actual = new ArrayList <Integer>(); 预期ArrayList <Integer> =新的ArrayList <Integer>(); actual.add(1); Expected.add(2); assertThat(actual,hasItems(expected));
ripper234 2009年


2

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
}

您可以随时使用hasItems(expected1.toArray(new String[expected1.size()]))。它将为您提供更好的故障消息。
meustrus
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.