In Assertj Core you can compare ojects field by field recursively.
In this test address.countryCode differ in the two objects:
@Test
public void shouldBeEqual() {
Person person1 = createPerson();
Person person2 = createPerson2();
assertThat(person1)
.usingRecursiveComparison()
.isEqualTo(person2);
}
I get error gessage:
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).
When you get the actual field difference in the error message like above it is very helpful, but if I have a list and want to verify the content of the list:
@Test
public void shouldBeEqual2() {
List<Person> personList = List.of(createPerson(), createPerson2());
assertThat(personList)
.hasSize(2)
.usingRecursiveFieldByFieldElementComparator()
.containsExactlyInAnyOrder(createPerson(), createPerson());
}
I get error message:
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).
Is it not possible to get the actual field difference here like in the first example?