2

I want to compare two objects (DTO and an Entity) using AssertJ's recursive comparison, for purpose of unit-testing DTO->Entity mapper. Both of these objects have fields with pretty much the same values, but some of the fields have different names between these two objects. That results in following error:

DTO can't be compared to Entity as Entity does not declare all DTO fields, it lacks these: [dtoFieldA, dtoFieldB, dtoFieldC]

I've tried following configuration, but without luck:

 assertThat(DTO)
    .usingRecursiveComparison(RecursiveComparisonConfiguration.builder()
    .withEqualsForFields(fieldAPRedicate, "dtoFieldA")
    .withEqualsForFields(fieldBPRedicate, "dtoFieldB")
    .withEqualsForFields(fieldCPRedicate, "dtoFieldC")
    .build())
.isEqualTo(Entity)

BiPredicate<DTO, Entity> fieldAPRedicate = (d, e) -> d.dtoFieldA().equals(e.entityFieldA());
BiPredicate<DTO, Entity> fieldBPRedicate = (d, e) -> d.dtoFieldB().equals(e.entityFieldB());
BiPredicate<DTO, Entity> fieldCPRedicate = (d, e) -> d.dtoFieldC().equals(e.entityFieldC());

Compared classess:

DTO:

public class DTO {
   protected String sameNameField1;
   protected String sameNameField2;
   protected String dtoFieldA;
   protected String dtoFieldB;
   protected String dtoFieldC;
}

Entity:

public class Entity {
   protected String sameNameField1;
   protected String sameNameField2;
   protected String entityFieldA;
   protected String entityFieldB;
   protected String entityFieldC;
}

How to configure assertJ for such case?

  • why not write a custom mapper (`DTO dtoFrom(Entity entity) { ... }`) ? If not, how you can be sure `fieldA` value must match with `fieldA'` value? – josejuan Sep 22 '21 at 15:51
  • AssertJ is in that case used specifically to test such mapper, therefore I have specified that certain fields have to match the others – Bartłomiej Adamczyk Sep 22 '21 at 21:25

1 Answers1

5

I think the best you can do at the moment is to ignore fields as there is not support in the recursive comparison to compare fields with different names, ignoring doc is there: https://assertj.github.io/doc/#assertj-core-recursive-comparison-ignoring-fields

If you absolutely require to compare DTO.a field against Entity.b field, the best option is to define a custom comparison method that would know which field to compare with which field, but there is nothing really helpful for doing in AssertJ (usingComparison() exists but the generic type won't allow to compare your DTO with an Entity unless you case everything to Object but at this point the workaround is not really worth it anymore).

Joel Costigliola
  • 6,308
  • 27
  • 35