I'm attempting to write a Junit test which should test if the order of elements in two LinkedHashSets are the same. The follwoing is my existing code:
Assert.assertEquals(
Sets.newLinkedHashSet(Arrays.asList("a","d","c","b")),
conf.getSetInfo()
);
This test is successful even if I give it compares a,d,c,b against a,b,c,d and thus not considering the ordering of elements. How can I go about asserting based on the ordering?
HashSet, LinkedHashSet and TreeSet are the implementations of Set interface which does not allow duplicate elements. In this tutorial we will see the differences between them. Fail-Fast Iterator is returned by HashSet, LinkedHashSet and TreeSet.
When cycling through LinkedHashSet using an iterator, the elements will be returned in the order in which they were inserted. Contains unique elements only like HashSet. It extends the HashSet class and implements the Set interface. Maintains insertion order.
Official JUnit documentation: assertEquals: Asserts that two objects are equal. assertSame: Asserts that two objects refer to the same object. In other words. assertEquals: uses the equals() method, or if no equals() method was overridden, compares the reference between the 2 objects.
org.junit If you allocate external resources in a Before method you need to release them after the test runs. Annotating a public void method with @After causes that method to be run after the Test method. All @After methods are guaranteed to run even if a Before or Test method throws an exception.
When you compare two Lists for equality, the ordering of the elements is taken into account. So simply convert the original LinkedHashSet into a List for assertion purposes.
List<String> expected = Arrays.asList("a", "d", "c", "b");
Assert.assertEquals(
expected,
new ArrayList<>(conf.getSetInfo())
);
LinkedHashSet is a Set (albeit one with guaranteed iteration order) and thus ordering is ignored in its equals()
implementation. Further reading.
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