Junit 和 Hamcrest 的单元测试失败 - 无法将数据与两个列表对象进行比较

Unit test failing with Junit and Hamcrest - Not able to compare data with two List objects

我有以下测试,实际上是断言两个列表中的数据。但是即使数据相同,测试也没有通过。我用谷歌搜索并找到了指向使用 assertThat(actual, containsInAnyOrder(expected.toArray())); 但运气不佳的 SO 链接。

@Test
public void testGetOrderLines() {
    List<OrderLine> expResult = new ArrayList<>();
    OrderLine orderLine = new OrderLine(100, 5, "http://image-url.com", "Baby Gym",
            1, "physical", "http://product-url.com", 100, "pcs", "100-123");
    expResult.add(orderLine);
    List<OrderLine> result = instance.getOrderLines();
    assertThat(expResult, containsInAnyOrder(result.toArray()));
}

错误:

Failed tests: AuthorizationRequestTest.testGetOrderLines:92 Expected: iterable over [http://image-url.com,name=Baby Gym,quantity=1,type=physical,productUrl=http://product-url.com,unitPrice=100,quantityUnit=pcs,reference=100-123]>] in any order but: Not matched: http://image-url.com,name=Baby Gym,quantity=1,type=physical,productUrl=http://product-url.com,unitPrice=100,quantityUnit=pcs,reference=100-123]>

如果您没有机会实现 equals() 方法,您可以使用基于反射的相等断言。例如unitils。它还适用于列表或数组中包含的对象。请注意,如果顺序可能不同,则必须使用宽松顺序比较器模式。这是一个例子:

import static org.junit.Assert.*;
import org.junit.Test;
import org.unitils.reflectionassert.ReflectionComparatorMode;
import static org.unitils.reflectionassert.ReflectionAssert.*;
import java.util.Arrays;
import java.util.List;

public class ReflectionEqualsTest {

    public static class A {
        private String x;

        public A(String text) {
            this.x = text;
        }
    }

    @Test
    public void testCompareListsOfObjectsWithoutEqualsImplementation() throws Exception {
        List<A> list = Arrays.asList(new A("1"), new A("2"));
        List<A> equalList = Arrays.asList(new A("1"), new A("2"));
        List<A> listInDifferentOrder = Arrays.asList(new A("2"), new A("1"));

        assertNotEquals(list, equalList);
        assertNotEquals(list, listInDifferentOrder);

        assertReflectionEquals(list, equalList);
        assertReflectionEquals(list, listInDifferentOrder, 
                        ReflectionComparatorMode.LENIENT_ORDER);
    }
}