views:

647

answers:

2

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
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
+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
Ooh, I hadn't realised hamcrest had made it into the junit distro. Go Nat!
skaffman
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
Use the above code snippet and throw in an additional assertTrue(l.size() == 2)
aberrant80
Meh, ugly. In NUnit that'sCollectionAssert.AreEqual( Collection expected, Collection actual );
ripper234
Isn't that just assertTrue(collection1.equals(collection2)); ?
Esko
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
Google have found another Stackoverflow answer that I was looking for!
Mykola Golubyev