在Assertj中,您可以逐个字段递归地比较ojects字段。
在这个测试中,address.countryCode在两个对象中不同:
@Test
public void shouldBeEqual() {
Person person1 = createPerson();
Person person2 = createPerson2();
assertThat(person1)
.usingRecursiveComparison()
.isEqualTo(person2);
}我得到错误信息:
java.lang.AssertionError:
Expecting actual:
Person@4b44655e
to be equal to:
Person@290d210d
when recursively comparing field by field, but found the following difference:
field/property 'address.countryCode' differ:
- actual value : "US"
- expected value: "CA"
The recursive comparison was performed with this configuration:
- no overridden equals methods were used in the comparison (except for java types)
- these types were compared with the following comparators:
- java.lang.Double -> DoubleComparator[precision=1.0E-15]
- java.lang.Float -> FloatComparator[precision=1.0E-6]
- java.nio.file.Path -> lexicographic comparator (Path natural order)
- actual and expected objects and their fields were compared field by field recursively even if they were not of the same type, this allows for example to compare a Person to a PersonDto (call strictTypeChecking(true) to change that behavior).当您得到上述错误消息中的实际字段差异时,这是非常有用的,但是如果我有一个列表并希望验证列表的内容:
@Test
public void shouldBeEqual2() {
List<Person> personList = List.of(createPerson(), createPerson2());
assertThat(personList)
.hasSize(2)
.usingRecursiveFieldByFieldElementComparator()
.containsExactlyInAnyOrder(createPerson(), createPerson());
}我收到错误消息:
java.lang.AssertionError:
Expecting actual:
[Person@4fe767f3, Person@18ce0030]
to contain exactly in any order:
[Person@2805c96b, Person@4445629]
elements not found:
[Person@4445629]
and elements not expected:
[Person@18ce0030]
when comparing values using recursive field/property by field/property comparator on all fields/properties using the following configuration:
- no overridden equals methods were used in the comparison (except for java types)
- these types were compared with the following comparators:
- java.lang.Double -> DoubleComparator[precision=1.0E-15]
- java.lang.Float -> FloatComparator[precision=1.0E-6]
- java.nio.file.Path -> lexicographic comparator (Path natural order)
- actual and expected objects and their fields were compared field by field recursively even if they were not of the same type, this allows for example to compare a Person to a PersonDto (call strictTypeChecking(true) to change that behavior).像第一个例子那样,这里不可能得到实际的字段差异吗?
发布于 2022-03-21 09:48:30
目前不可能这样做,因为为containsExactlyInAnyOrder构建的错误消息不知道断言失败的根本原因,在我们的示例中,它不知道比较差异,它只知道断言失败并构建一个通用错误消息。
我们已经考虑过支持这个用例,但是用当前设计错误的方式来实现并不简单。
https://stackoverflow.com/questions/71539898
复制相似问题