Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare if a DTO is equal with a Domain Model in Java

I have started trying to get my Unit Tests as cleaner as possible and I came across with: How could I compare in a clean way a DTO and a Domain Model (DM) which contain more than 10 attributes and share some of them but not all?

Detail: There can be shared attributes but with different type or different name so reflection cannot be used in this case.

Example:

class Person {
     private String id;
     private String name;
     private String lastName;
     private Date   dateOfbirth;
}

class PersonDto{
     private String id;
     private String name;
     private String lastName;
     private int    dateOfBirth;
}

The DTO should not hold any kind of complex logic as it is only to transfer Data between Client - Controller - Service.

The DM to persist and provide information between Service - Repository layers. But it should not have any kind of complex logic (equals and hashcode so far).

Then I was thinking... Should I create a TestHelperComparator to perform this operation? or implement in the DTO or DM a method to Compare to each other? or what is the best practice in this case?

like image 785
dbenor Avatar asked Dec 09 '25 19:12

dbenor


1 Answers

You probably have the DTO to domain mapping logic somewhere in your code e.g. PersonToDtoMapper class. Make sure the mapping logic is encapsulated in a separate class. You can then reuse this mapper class in your unit tests, translating from one format to another when you have to compare.

As long as PersonToDtoMapper is tested in it's own test there reusing it in other tests shouldn't be a problem, the errors will be easy to spot if PersonToDtoMapperTest fails.

like image 102
Karol Dowbecki Avatar answered Dec 11 '25 07:12

Karol Dowbecki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!