java - 逐个字段比较两个列表与元素
问题描述
我有以下结构
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;
}
没有一个类实现等于。我想比较两个ComplexClazz
s 的相等性,而与列表中的顺序无关。
在我的遗留代码中,这到目前为止已解决
ReflectionAssert.assertReflectionEquals(expectedResult, actualResult, ReflectionComparatorMode.LENIENT_ORDER);
但我想摆脱过时的unitils
库并使用例如assertj。
我尝试与 withassertThat(actualResult).containsExactlyInAnyOrder(expectedResult);
结合使用,usingFieldByFieldElementComparator
但无法使其工作。
任何想法如何比较这些对象?
解决方案
尝试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);
推荐阅读
- excel - Excel - 如果特定列中的单元格包含在另一列中找到的值,则删除行
- typescript - 如何在打字稿中创建二维对象数组
- javascript - 在 Jest 中测试嵌套的 Promise
- python - 使用 python 创建排序的 sqlite 数据库
- c++ - 如何编写可以包含不同强类型枚举作为错误代码的错误结构?
- python - pymc3确定性中的广播形状
- python - 如何在 ArcGIS 安装的 Python 2.7 中安装 pip
- javascript - 接近尾声的倒计时计时器
- c# - 使用 google drive API 启动程序时出错
- javascript - 在 .each() 函数中设置超时