Home > OS >  Do I need ArgumentCaptor for checking saved uuid?
Do I need ArgumentCaptor for checking saved uuid?

Time:11-23

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:

  1. Using request instead of any() you can verify also the setName directive you've inserted before the save call (obviously only if the name field has its own role in the equals implementation of the TaxLabelRequest object).
  2. Using the Answer you are verifying that the UUID you are looking for is set by the saving operation invoked with the right request parameter.

Note that you can replace the anonymous object Answer with a lambda function.

  • Related