Jordi
Jordi

Reputation: 23277

assertj: compare fields between dto and entity classes

I need to compare a DTO class with its Entity class.

For example, an AddressDTO class would be:

@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class AddressDTO {

    private StringTypeDTO text;
    private List<StringTypeDTO> line;
    private StringTypeDTO city;
    private StringTypeDTO district;
    private StringTypeDTO state;
    private StringTypeDTO postalCode;
    private StringTypeDTO country;

}

and my AddressEntity class would be:

@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Address {

    private StringType text;
    private List<StringType> line;
    private StringType city;
    private StringType district;
    private StringType state;
    private StringType postalCode;
    private StringType country;

}

Is there any way to compare those two objects using assertj?

StringType:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class StringTypeDTO {

    private String value;
    
}

And StringType:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class StringType {

    private String value;
    
}

I want to avoid to make code like:

assertThat dto.field1 is equals to entity.field1 of object
assertThat dto.field2 is equals to entity.field2 of object
assertThat dto.field3 is equals to entity.field3 of object

Any ideas?

Upvotes: 3

Views: 2275

Answers (1)

Stefano Cordio
Stefano Cordio

Reputation: 2267

The field-by-field recursive comparison is what you are looking for:

AddressDTO addressDTO = new AddressDTO(...);
AddressEntity addressEntity = new AddressEntity(...);

assertThat(addressDTO).usingRecursiveComparison()
                      .isEqualTo(addressEntity);

Upvotes: 3

Related Questions