【问题标题】:Unit test failing with Junit and Hamcrest - Not able to compare data with two List objectsJunit 和 Hamcrest 的单元测试失败 - 无法将数据与两个 List 对象进行比较
【发布时间】:2017-05-03 20:46:45
【问题描述】:

我有以下测试,实际上是在两个列表中断言数据。但即使数据相同,测试也没有通过。我用谷歌搜索并找到指向使用 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()));
}

错误:

失败的测试: AuthorizationRequestTest.testGetOrderLines:92 预期:可按任何顺序迭代 [http://image-url.com,name=Baby Gym,quantity=1,type=physical,productUrl=http://product-url.com,unitPrice=100,quantityUnit=pcs,reference=100-123]>] 但是:不匹配:http://image-url.com,name=Baby Gym,quantity=1,type=physical,productUrl=http://product-url.com,unitPrice=100,quantityUnit=pcs,reference=100-123]>

【问题讨论】:

  • 我认为equals 的实现是明智的?
  • @JoeC 和 hashCode,大概。
  • 不,没有 hashCode 和 equals 实现。由于模型类在我的控制之下,我当然可以继续实现上述两种方法,但只是想知道如果这是来自 3rd 方 jar 的类,我将如何进行测试?
  • 你去吧!
  • @Darshan - 我的第二个问题仍然存在。如果类是在我们无法控制的第 3 方 jar 中定义的,您将如何比较这两个列表?

标签: java unit-testing testing junit hamcrest


【解决方案1】:

如果您没有机会实现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);
    }
}

【讨论】:

  • 好主意。当然,这是以通常的“反射”成本为代价的(因为你真的不知道这些容器有哪些类型的字段,确切地比较了什么);但我不知道 assertReflectionEquals()。不是我通常会使用的东西,但可以肯定的是:当你需要它时,使用库比自己实现断言更好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多