How would you succinctly assert the equality of collections
elements, specifically a Set
in JUnit 4
?
views:
361answers:
4
A:
Check this article. One example from there:
@Test
public void listEquality() {
List<Integer> expected = new ArrayList<Integer>();
expected.add(5);
List<Integer> actual = new ArrayList<Integer>();
actual.add(5);
assertEquals(expected, actual);
}
Roman
2010-02-22 18:58:23
+1
A:
You can just assert that the two Sets are equal to one another, which invokes the Set equals() method.
public class SimpleTest {
private Set<String> setA;
private Set<String> setB;
@Before
public void setUp() {
setA = new HashSet<String>();
setA.add("Testing...");
setB = new HashSet<String>();
setB.add("Testing...");
}
@Test
public void testEqualSets() {
assertEquals( setA, setB );
}
}
This test will pass if the two Sets are the same size and contain the same elements.
Bill the Lizard
2010-02-22 19:08:51
A:
A particularly interesting case is when you compare
java.util.Arrays$ArrayList<[[name,value,type], [name1,value1,type1]]>
and
java.util.Collections$UnmodifiableCollection<[[name,value,type], [name1,value1,type1]]>
So far, the only solution I see is to change both of them into sets
assertEquals(new HashSet<CustomAttribute>(customAttributes), new HashSet<CustomAttribute>(result.getCustomAttributes()));
Or I could compare them element by element.
Arkadiy
2010-08-30 19:44:47