Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Compare complex objects excluding some fields for JUnit

I tried the Unitils tool which is really great, but doesn't provide you an option for excluding fields. The only way by doing this is to set null the objects and enable the IGNORE_DEFAULTS flag, but in my case, it's not helpful, since I've got some ids autogenerated by the system. So if I could just add the id to an exclude list it would be perfect.

I also tried Mockito's ReflectionEquals but it was not helpful, since I need a field-to-field comparison.

Is there something else helpful? I have been searching for hours without success.

Thank you in advance!

like image 645
Harter Oliver Avatar asked Feb 05 '26 06:02

Harter Oliver


1 Answers

You could solve your problem by using AssertJ. It can do field-by-field recursive comparison with options to ignore fields by name, regex or type.

assertThat(sherlock)
  .usingRecursiveComparison()
  .ignoringFields("name", "home.address.street")
  .isEqualTo(moriarty);

like image 119
Frank Neblung Avatar answered Feb 06 '26 20:02

Frank Neblung