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

前端 未结 7 1589
星月不相逢
星月不相逢 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 01:01

    • My answer about whether Iterables.elementsEqual is best choice:

    Iterables.elementsEqual is enough to compare 2 Lists.

    Iterables.elementsEqual is used in more general scenarios, It accepts more general types: Iterable. That is, you could even compare a List with a Set. (by iterate order, it is important)

    Sure ArrayList and LinkedList define equals pretty good, you could call equals directly. While when you use a not well defined List, Iterables.elementsEqual is the best choice. One thing should be noticed: Iterables.elementsEqual does not accept null

    • To convert List to array: Iterables.toArray is easer.

    • For unit test, I recommend add empty list to your test case.

提交回复
热议问题