What's the best way to validate the values of a Set in a unit test?
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 wi开发者_如何学JAVAll always return the items in the same order.
Does anyone have any preferred method of validating a Set?
Peter
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);
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
精彩评论