How to JUnit test that two List contain the same elements in the same order?

前端 未结 7 1592
星月不相逢
星月不相逢 2021-02-01 00:39

Context

I am writing a simple JUnit test for the MyObject class.

A MyObject can be created from a static factory met

7条回答
  •  难免孤独
    2021-02-01 00:46

    org.junit.Assert.assertEquals() and org.junit.Assert.assertArrayEquals() do the job.

    To avoid next questions: If you want to ignore the order put all elements to set and then compare: Assert.assertEquals(new HashSet(one), new HashSet(two))

    If however you just want to ignore duplicates but preserve the order wrap you list with LinkedHashSet.

    Yet another tip. The trick Assert.assertEquals(new HashSet(one), new HashSet(two)) works fine until the comparison fails. In this case it shows you error message with to string representations of your sets that can be confusing because the order in set is almost not predictable (at least for complex objects). So, the trick I found is to wrap the collection with sorted set instead of HashSet. You can use TreeSet with custom comparator.

提交回复
热议问题