如何解决逐个字段比较两个带有元素的列表
我有以下结构
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;
}
没有一个类实现equals。我想比较两个 ComplexClazz
的相等性,而与列表中的顺序无关。
ReflectionAssert.assertReflectionEquals(expectedResult,actualResult,ReflectionComparatorMode.LENIENT_ORDER);
但我想摆脱过时的 unitils
库并使用例如断言j。
我尝试将 assertthat(actualResult).containsExactlyInAnyOrder(expectedResult);
与 usingFieldByFieldElementComparator
结合使用,但无法使其工作。
任何想法如何比较这些对象?
解决方法
尝试使用 AssertJ recursive comparison 并使用 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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。