JUnit 4 compare Sets

后端 未结 9 1196
-上瘾入骨i
-上瘾入骨i 2020-12-24 03:59

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

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-24 04:41

    You can assert that the two Sets are equal to one another, which invokes the Set equals() method.

    public class SimpleTest {
    
        private Set setA;
        private Set setB;
    
        @Before
        public void setUp() {
            setA = new HashSet();
            setA.add("Testing...");
            setB = new HashSet();
            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.

提交回复
热议问题