views:

38

answers:

2

Okay, often I'll have a method that returns a Set of some sort. The problem with unit testing such a method is that there is no guarantee an iteration over the set will always return the items in the same order.

Does anyone have any preferred method of validating a Set?

Peter

A: 

Two sets are equal, meaning they contain the same items, if they both contain one another

Assert.assertTrue(s1.containsAll(s2) && s2.containsAll(s1))

There's also SetUtils.isEqualSet

sblundy
+1  A: 

Just put your expected values in a Set and then use assertEquals on the expected and actual set. That works a charm, e.g.

Set<String> expected = new HashSet<String>(Arrays.asList("expected", "items"));
...
Set<String> actual = ...;
Assert.assertEquals(expected, actual);
Dean Povey
Hey, yeah. I didn't know you could do that. From the Java 6 AbstractSet javadocs:
Risser
Compares the specified object with this set for equality. Returns true if the given object is also a set, the two sets have the same size, and every member of the given set is contained in this set. This ensures that the equals method works properly across different implementations of the Set interface.This implementation first checks if the specified object is this set; if so it returns true. Then, it checks if the specified object is a set whose size is identical to the size of this set; if not, it returns false. If so, it returns containsAll((Collection) o).
Risser
containsAll uses contains, and contains uses the .equals method. For sets of simple pojos, or anything that has a nice .equals method, that's pretty nifty. Thanks!
Risser
You're welcome :-)
Dean Povey