How to compare recursively ignoring given fields using assertJ?
With latest 'Recursive comparison api improvements' from AssertJ release 3.12.0 it's possible now to do a recursive comparison and ignore fields:
Assertions.assertThat(objActual)
.usingRecursiveComparison()
.ignoringFields("uniqueId", "otherId")
.ignoringFieldsMatchingRegexes(".*someId")
.ignoringOverriddenEqualsForTypes(MyData.class, MyDataItem.class)
.isEqualTo(objExpected);
I couldn't get it to ignore some fields but I managed to temporarily solve it by introducing a comparator for the fields which I want to ignore and always evaluated them to true. This is not fluent but a temporary solution to get the job done.
assertThat(object).usingComparatorForFields((x,y)->0,"field1","field2").isEqualToComparingFieldByFieldRecursively(expectedObject);
This has an issue as of April 13, 2017. It doesn't work when the fields which the comparator is trying to compare are null. This is an issue when one of objects is null
not if both are null
.