Reputation: 53
I'm wondering what's the best approach to test the Service layer when I use Mapper and Repository inside my Service:
public ExpenseDto create(NewExpenseDto newExpenseDto) {
ExpenseEntity expenseEntity = expenseMapper.fromNewDtoToEntity(newExpenseDto);
ExpenseEntity savedExpenseEntity = expenseRepository.save(expenseEntity);
ExpenseDto expenseDto = expenseMapper.fromEntityToDto(savedExpenseEntity);
return expenseDto;
}
I have written a test like this below, but I'm not sure if it's the best way - in accordance with the rules of programming.
@ExtendWith(MockitoExtension.class)
class ExpenseServiceTest {
@Mock
private ExpenseRepository expenseRepository;
@Mock
private ExpenseMapper expenseMapper;
@InjectMocks
private ExpenseService expenseService ;
@Test
void givenNewExpenseDto_whenNewExpense_thenExpenseDtoNotNull() {
//Given
NewExpenseDto newExpenseDto = new NewExpenseDto();
ExpenseEntity expenseEntity = new ExpenseEntity();
ExpenseDto expenseDto = new ExpenseDto();
//When
when(expenseMapper.fromNewDtoToEntity(any())).thenReturn(expenseEntity);
when(expenseRepository.save(any())).thenReturn(expenseEntity);
when(expenseMapper.fromEntityToDto(any())).thenReturn(expenseDto);
ExpenseDto savedExpenseDto = expenseService.create(newExpenseDto);
//Then
assertNotNull(savedExpenseDto, "Saved ExpenseDto is null");
}
...
}
Upvotes: 1
Views: 1134
Reputation: 139
I have some remarks of your test :
it is better to test your method by passing to it an instance with parameters, so you can ensure that your instance is saved with the right values.
NewExpenseDto newExpenseDto = new NewExpenseDto(param1, param2, param3);
you should specify parameters for your mocks when(expenseMapper.fromNewDtoToEntity(any()))
becomes :
when(expenseMapper.fromNewDtoToEntity(new NewExpenseDto(eq(param1), eq(param2), eq(param3))))
you should not assert only on the nullability of your instance but also on the fields of savedExpenseDto
assertEquals(expenseRepository.getParam1(), value1);
you should also verify the call with right values of the save
method of your repository expenseRepository
verify(expenseRepository).save(new ExpenseEntity(param1, param2, param3))
for this I suppose that you override hash and equals method for ExpenseEntity
Upvotes: 2