Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit test for order in LinkedHashSet [duplicate]

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?

like image 700
seriousgeek Avatar asked Jul 18 '17 14:07

seriousgeek


People also ask

Is duplicates allowed in LinkedHashSet?

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.

How does LinkedHashSet maintain order?

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.

What is assertSame in JUnit?

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.

What is @after in JUnit?

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.


1 Answers

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.

like image 85
Jonik Avatar answered Sep 19 '22 13:09

Jonik