首页 > 解决方案 > 逐个字段比较两个列表与元素

问题描述

我有以下结构

public class ComplexClazz {

    private List<A> a;
    private List<B> b;
}

public class A {
    private String someString;
    private List<C> c;
}

public class B {
   private BigDecimal someBigDecimal;
}

public class C {
   private String someString;
   private D d;
}

public class D {
   private String someString;
   private Integer someInt;
}

没有一个类实现等于。我想比较两个ComplexClazzs 的相等性,而与列表中的顺序无关。

在我的遗留代码中,这到目前为止已解决

ReflectionAssert.assertReflectionEquals(expectedResult, actualResult, ReflectionComparatorMode.LENIENT_ORDER);

但我想摆脱过时的unitils库并使用例如assertj。

我尝试与 withassertThat(actualResult).containsExactlyInAnyOrder(expectedResult);结合使用,usingFieldByFieldElementComparator但无法使其工作。

任何想法如何比较这些对象?

标签: javatestingjunitassertj

解决方案


尝试AssertJ 递归比较和使用ignoringCollectionOrder,例如:

public class Person {
   String name;
   List<Person> friends = new ArrayList<>();
   // no equals method
 }

 Person sherlock1 = new Person("Sherlock Holmes");
 sherlock1.friends.add(new Person("Dr. John Watson"));
 sherlock1.friends.add(new Person("Molly Hooper"));

 Person sherlock2 = new Person("Sherlock Holmes");
 sherlock2.friends.add(new Person("Molly Hooper"));
 sherlock2.friends.add(new Person("Dr. John Watson"));

 // assertion succeeds as friends collection order is ignored in the comparison
 assertThat(sherlock1).usingRecursiveComparison()
                      .ignoringCollectionOrder()
                      .isEqualTo(sherlock2);

 // assertion fails as friends collection order is not ignored in the comparison
 assertThat(sherlock1).usingRecursiveComparison()
                      .isEqualTo(sherlock2);

推荐阅读