Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit 4 compare Sets

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

like image 330
Eqbal Avatar asked Feb 22 '10 18:02

Eqbal


People also ask

How do I compare lists in JUnit?

Using JUnit We can use the logic below to compare the equality of two lists using the assertTrue and assertFalse methods. In this first test, the size of both lists is compared before we check if the elements in both lists are the same. As both of these conditions return true, our test will pass.

How do you assert a set in JUnit?

You can assert that the two Set s are equal to one another, which invokes the Set equals() method. This @Test will pass if the two Set s are the same size and contain the same elements.

How do you compare sets in Java?

The equals() method of java. util. Set class is used to verify the equality of an Object with a Set and compare them. The method returns true if the size of both the sets are equal and both contain the same elements.

How do you compare two lists with assert?

To compare two lists specifically, TestNG's Assert class has a method known as assertEquals(Object actual, Object expected) and there is an extended version of this method with customized message as assertEquals(Object actual, Object expected, String message). if the elements of the lists are in the same order.


1 Answers

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.

like image 107
Bill the Lizard Avatar answered Oct 09 '22 07:10

Bill the Lizard