Recently we encountered some conflict during the development of our system. We discovered, that we have 3 different approaches to testing in our team, and we need to decide which one is best and check if there is nothing better than this.
First, let's face some facts:
- we have 3 data layers in the system (DTOs, domain objects, tables)
- we are using mappers generated with mapstruct to map objects of each layer to another
- we are using mockito
- we are unit-testing each of our layers
Now the conflict: Let's assume that we want to test ExampleService
which is using ExampleModelMapper
to map ExampleModel
to ExampleModelDto
and doing some additional business logic which needs testing. We can verify the correctness of returned data in three different ways:
a) We can manually compare each field of a returned object to an expected result:
assertThat(returnedDto)
.isNotNull()
.hasFieldOrPropertyWithValue("id", expectedEntity.getId())
.hasFieldOrPropertyWithValue("address", expectedEntity.getAddress())
.hasFieldOrPropertyWithValue("orderId", expectedEntity.getOrderId())
.hasFieldOrPropertyWithValue("creationTimestamp", expectedEntity.getCreationTimestamp())
.hasFieldOrPropertyWithValue("price", expectedEntity.getPrice())
.hasFieldOrPropertyWithValue("successCallbackUrl", expectedEntity.getSuccessCallbackUrl())
.hasFieldOrPropertyWithValue("failureCallbackUrl", expectedEntity.getFailureCallbackUrl())
b) We can use real mapper (same as in normal logic) to compare two objects:
assertThat(returnedDto).isEqualToComparingFieldByFieldRecursivly(mapper.mapToDto(expectedEntity)))
c) And finally, we can mock mapper and its response:
final Entity entity = randomEntity();
final Dto dto = new Dto(entity.getId(), entity.getName(), entity.getOtherField());
when(mapper.mapToDto(entity)).thenReturn(dto);
We want to make tests as good as possible while keeping them elastic and change-resistant. We also want to keep to DRY principle.
We are happy to hear any pieces of advice, comments, pros, and cons of each method. We are also open to see any other solutions.
Greetings.