Search code examples
javajunitmockinghamcrest

JUnit compare objects in collections except specified fields in contained objects


JUnit tests...

It needs to compare 2 single elements excepting some fields. I can use assertj for this:

Assertions.assertThat(actual).isEqualToIgnoringGivenFields(except, "id", "innerCollection");

and it works good. But it's not enough. I need to compare inner collections also. I know that only ids are different in inner collection. Is it possible to compare ones like

Assertions.assertThat(to.getInnerCollection()).isEqualToIgnoringGivenFields(from.getInnerCollection()
, {except fields in collection elements});

Solution

  • In this case, I would rather consider to create your own custom matcher.

    That is actually a straight-forward task; you can find a detailed example here.