CollectionAssert JUnit中?
题
是否有平行于NUnit的的 CollectionAssert
?
解决方案
使用JUnit 4.4你可以用 Hamcrest 码(不用担心,它的出货量一起使用assertThat()
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流利断言。恕我直言,他们比Hamcrest(同样强大,可扩展等),使用起来更加方便和更好的IDE支持,得益于流畅的界面有。请参见 https://github.com/alexruiz/fest-断言-2.X /维基/使用巨星-断言
约阿希姆·绍尔的解决方案是好的,但如果你已经有了,你要验证在你的结果预期的数组不起作用。这可能会来,当你已经在你的测试,你要的结果比较生成或不变的预期,或者你有你所期望的结果要合并多个期望。因此,不是使用匹配器可以可以只使用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
}
不隶属于 StackOverflow