How to compare recursively ignoring given fields using assertJ?

29,563

Solution 1

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.

Solution 2

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);
Share:
29,563
Tarun Maganti
Author by

Tarun Maganti

Learner.

Updated on August 05, 2020

Comments

  • Tarun Maganti
    Tarun Maganti over 3 years

    AssertJ has isEqualToIgnoringGivenFields and isEqualToComparingFieldByFieldRecursively.

    But, there is no way I can compare two objects recursively by ignoring some fields. As per this discussion, it must be in development.

    How to still get my assert's return value to be compared recursively but ignoring some fields. Is it possible in any other library or can I do it somehow using AssertJ?