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

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

    I prefer using Hamcrest because it gives much better output in case of a failure

    Assert.assertThat(listUnderTest, 
           IsIterableContainingInOrder.contains(expectedList.toArray()));
    

    Instead of reporting

    expected true, got false

    it will report

    expected List containing "1, 2, 3, ..." got list containing "4, 6, 2, ..."

    IsIterableContainingInOrder.contain

    Hamcrest

    According to the Javadoc:

    Creates a matcher for Iterables that matches when a single pass over the examined Iterable yields a series of items, each logically equal to the corresponding item in the specified items. For a positive match, the examined iterable must be of the same length as the number of specified items

    So the listUnderTest must have the same number of elements and each element must match the expected values in order.

提交回复
热议问题