逐字段比较两个列表的元素

Compare two lists with elements field-by-field

我有以下结构

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;
}
类 的

none 实现了 equals。我想比较两个 ComplexClazz 是否相等,而与列表中的顺序无关。

在我的遗留代码中,目前已通过

解决了这个问题
ReflectionAssert.assertReflectionEquals(expectedResult, actualResult, ReflectionComparatorMode.LENIENT_ORDER);

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

我尝试将 assertThat(actualResult).containsExactlyInAnyOrder(expectedResult);usingFieldByFieldElementComparator 结合使用,但无法正常工作。

关于如何比较这些对象有什么想法吗?

试试 AssertJ recursive comparison and use 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);