5

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?

Jonik
  • 80,077
  • 70
  • 264
  • 372
seriousgeek
  • 992
  • 3
  • 13
  • 29
  • @Tim C'mon now. _If you want to assert identical iteration order, you could copy both iterations into Lists and compare the lists._ Are you peeved about `LinkedHashSet` vs `LinkedHashMap`? – Sotirios Delimanolis Jul 18 '17 at 14:23
  • Unless we are talking about **your** own implementation of a LinkedHashSet; or some homework given to you: there is no point in testing an implementation that is not yours. In other words: why do you think you have to verify built-in APIs? – GhostCat Jul 19 '17 at 07:20

1 Answers1

6

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.

Jonik
  • 80,077
  • 70
  • 264
  • 372