CollectionAssert in jUnit?

旧城冷巷雨未停 提交于 2019-11-27 11:31:23
Joachim Sauer

Using JUnit 4.4 you can use assertThat() together with the Hamcrest code (don't worry, it's shipped with JUnit, no need for an extra .jar) to produce complex self-describing asserts including ones that operate on collections:

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

Using this approach you will automagically get a good description of the assert when it fails.

skaffman

Not directly, no. I suggest the use of Hamcrest, which provides a rich set of matching rules which integrates nicely with jUnit (and other testing frameworks)

Take a look at FEST Fluent Assertions. IMHO they are more convenient to use than Hamcrest (and equally powerful, extensible etc) and have better IDE support thanks to fluent interface. See https://github.com/alexruiz/fest-assert-2.x/wiki/Using-fest-assertions

Joachim Sauer's solution is nice but doesn't work if you already have an array of expectations that you want to verify are in your result. This might come up when you already have a generated or constant expectation in your tests that you want to compare a result to, or perhaps you have multiple expectations you expect to be merged in the result. So instead of using matchers you can can just use List::containsAll and assertTrue For Example:

@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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!