Is there a jUnit parallel to NUnit's CollectionAssert?
+3
A:
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)
skaffman
2009-07-06 12:32:09
This does not compile for some reason (see http://stackoverflow.com/questions/1092981/hamcrests-hasitems):ArrayList<Integer> actual = new ArrayList<Integer>(); ArrayList<Integer> expected = new ArrayList<Integer>(); actual.add(1); expected.add(2); assertThat(actual, hasItems(expected));
ripper234
2009-07-07 15:23:07
+8
A:
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.
Joachim Sauer
2009-07-06 12:32:52
Ooh, I hadn't realised hamcrest had made it into the junit distro. Go Nat!
skaffman
2009-07-06 12:49:35
If I want to assert l is composed of items ("foo", "bar"), but no other items exists - is there some easy syntax for that?
ripper234
2009-07-06 12:57:36
Use the above code snippet and throw in an additional assertTrue(l.size() == 2)
aberrant80
2009-07-06 13:12:51
Meh, ugly. In NUnit that'sCollectionAssert.AreEqual( Collection expected, Collection actual );
ripper234
2009-07-06 14:08:58
You are free to write your own CollectionAssert.AreEqual(Collection col1, Collection col2) using example above. You'll needed about 5 minutes to made this.
Vanger
2009-07-06 15:00:36
Google have found another Stackoverflow answer that I was looking for!
Mykola Golubyev
2009-08-06 15:15:45