I am trying to write a unit test for the following service method (create()):
public CommandDTO create(TaxLabelRequest taxLabelRequest) {
return saveTaxLabel(new TaxLabel(), taxLabelRequest);
}
private CommandDTO saveTaxLabel(TaxLabel taxLabel, TaxLabelRequest taxLabelRequest) {
taxLabel.setName(taxLabelRequest.getName());
// maybe I can use ArgumentCaptor for `taxLabel`
final TaxLabel saved = taxLabelRepository.saveAndFlush(taxLabel);
return CommandDTO.builder().uuid(saved.getUuid()).build();
}
Here is my Unit Test:
public void test_create() {
final TaxLabelRequest request = new TaxLabelRequest();
request.setCountryUuid(UUID.fromString("00000000-0000-0000-0000-000000000001"));
request.setName("Name");
TaxLabel taxLabel = new TaxLabel();
taxLabel.setCountryUuid(request.getCountryUuid());
taxLabel.setName(request.getName());
taxLabel.setDescription(request.getDescription());
when(taxLabelRepository.saveAndFlush(any())).thenReturn(taxLabel);
CommandDTO result = taxLabelService.create(request);
// I have no idea how to check the result
assertEquals(taxLabel.getUuid(), result.getUuid());
}
So, should I use ArgumentCaptor so that I get the uuid value of the saved entity and then check if it is equal to taxLabel.getUuid()?
CodePudding user response:
Try with this:
String myuuid = ...;
when(taxLabelRepository.saveAndFlush(request)).thenAnswer(new Answer(){
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
textLabel.setUuid(myuuid);
return textLabel;
}
});
CommandDTO result = taxLabelService.create(request);
assertEquals(myuuid, result.getUuid());
In this manner you would test two more aspects:
- Using
requestinstead ofany()you can verify also thesetNamedirective you've inserted before thesavecall (obviously only if thenamefield has its own role in theequalsimplementation of theTaxLabelRequestobject). - Using the
Answeryou are verifying that the UUID you are looking for is set by the saving operation invoked with the rightrequestparameter.
Note that you can replace the anonymous object Answer with a lambda function.
