Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare recursively ignoring given fields using assertJ?

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?

like image 655
Tarun Maganti Avatar asked Apr 10 '17 06:04

Tarun Maganti


2 Answers

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); 
like image 63
Ovidiu Nistor Avatar answered Oct 06 '22 02:10

Ovidiu Nistor


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.

like image 39
Tarun Maganti Avatar answered Oct 06 '22 02:10

Tarun Maganti