How to compare recursively ignoring given fields using assertJ?

梦想与她 提交于 2019-12-01 18:04:07

问题


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?


回答1:


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);



回答2:


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.



来源:https://stackoverflow.com/questions/43316133/how-to-compare-recursively-ignoring-given-fields-using-assertj

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!