Junit test for ordering in LinkedHashSet

I am trying to write a Junit test that needs to check if the order of items in two LinkedHashSets is the same. The following is my existing code:

Assert.assertEquals(
            Sets.newLinkedHashSet(Arrays.asList("a","d","c","b")),
            conf.getSetInfo()
    );  

      

This test succeeds even if I give it a comparison of a, d, c, b with a, b, c, d and therefore does not consider the order of the elements. How can I approve based on order?

+3


source to share


1 answer


When you compare two Lists for Equality, the ordering of the elements is taken into account. So just convert the original LinkedHashSet to 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 with a guaranteed iteration order) and therefore its implementation is ignored in its implementation equals()

. Further reading .

+5


source







All Articles