Search code examples
javaunit-testingcollectionsjunit

JUnit 4 compare Sets


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


Solution

  • 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.