How would you succinctly assert the equality of Collection
elements, specifically a Set
in JUnit 4?
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.
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.
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.
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.
You can assert that the two Set
s 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 Set
s are the same size and contain the same elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With