JUnit 4 compare Sets

Eqbal picture Eqbal · Feb 22, 2010 · Viewed 103.9k times · Source

How would you succinctly assert the equality of Collection elements, specifically a Set in JUnit 4?

Answer

Bill the Lizard picture Bill the Lizard · Feb 22, 2010

You can 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.