0

mocking one service api which is again calling repository api it is giving nullpointer exception

creating savingAccount with some validation. trying to write junit testcase for rest end point using mocktio

it is giving nullpointerexception when(savingsProductService.findByName(anyString())).thenReturn(Optional.of(savingsProduct)); line in test file.

Controller file....

ResponseEntity<ResponseModel> createSavingsProduct(@RequestBody  final SavingsProduct savingsProduct, final HttpServletRequest request,
                                                           final HttpServletResponse response) throws Exception {

    Set<ConstraintViolation<Object>> errors= savingsProductService.checkValidation(savingsProduct,new BigInteger("1"));
    if(errors.size()>0)
    {
        List<String> messages = new ArrayList<>();
        ResponseModel responseModel = new ResponseModel("");
        for(ConstraintViolation<Object> constraintViolation: errors)
        {
            messages.add(constraintViolation.getMessage());
        }
        responseModel.setData(messages);

        return ResponseEntity.badRequest().body(responseModel);

    }
    savingsProductService.findByName(savingsProduct.getName())
            .ifPresent(product -> {throw ServiceException.conflict("Duplicate name: " + product.getName());});

//  savingsProductService.findByIdentifier(savingsProduct.getIdentifier())
//  .ifPresent(product -> {throw ServiceException.conflict("Duplicate product short name: " + product.getIdentifier());});

    savingsProductService.findByShortName(savingsProduct.getShortName())
            .ifPresent(product -> {throw ServiceException.conflict("Duplicate short name: " + product.getShortName());});


    log.info("*****Create Savings Product*************** ");
    this.commandGateway.process(new CreateSavingsProductCommand(request.getHeader("UUID"), savingsProduct));
    ResponseModel responseModel = new ResponseModel("Accepted the Savings Product created");
    return ResponseEntity.accepted().body(responseModel);
}

Servicefile...

public Optional<SavingsProduct> findByName(final String name) {
    return savingsProductRepository.findByName(name).map(SavingsProductMapper::map);
}

RepositoryFile...

Optional<SavingsProductEntity> findByName(String var1);

i am writing test for controller API like this.

@Test
public void createSavingsProduct() throws Exception {
    String testUrl = baseUrl + "/products";
    SavingsProduct savingsProduct = new SavingsProduct();
    savingsProduct.setName("Chocolate");
    savingsProduct.setShortName("Cho");

    CreateSavingsProductCommand createSavingsProductCommand = new CreateSavingsProductCommand(httpServletRequest.getHeader("UUID"), savingsProduct);
    Set<ConstraintViolation<Object>> errors = new HashSet<>();
    when(savingsProductService.checkValidation(savingsProduct,new BigInteger("1"))).thenReturn(errors);
    SavingsProductEntity savingsProduct1 = new SavingsProductEntity();
    savingsProduct1.setIdentifier(BigInteger.ONE);
    savingsProduct1.setName("xvm");

    //when(savingsProductRepository.findByName(anyString())).thenReturn(java.util.Optional.of(savingsProduct1));
    //when(savingsProductRepository.findByShortName(anyString())).thenReturn(java.util.Optional.of(savingsProduct1));

    when(savingsProductService.findByName(anyString())).thenReturn(Optional.of(savingsProduct));

    doNothing().when(commandGateway).process(createSavingsProductCommand);

    MvcResult result = mockMvc.perform(post(testUrl,httpServletRequest,httpServletResponse).content(new ObjectMapper().writeValueAsString(savingsProduct)).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)).andReturn();

    assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.ACCEPTED.value());
    verify(commandGateway).process(commandGateway);

}
second
  • 3,676
  • 2
  • 6
  • 22
gar
  • 109
  • 1
  • 6
  • I would try debugging and see what is null at that point –  Aug 21 '19 at 18:32
  • If the info you posted is correct `savingsProductService` is likely to be null. You did not include where and how you have created the mock for it. – second Aug 21 '19 at 18:47
  • it is failing before calling rest end point.at line savingsProductRepository.findByName(name).map(SavingsProductMapper::map);.......savingsProductRepository.findByName(name) this is returning null. So it is throwing null pointer. i have doubt if i am mocking service api then why it is checking inside code. i guess i have to mock repository api also . but not sure how ??? – gar Aug 21 '19 at 19:04
  • You will probably have to ask a new question. Avoid that the title includes the mentioning of the `NPE`, instead name it something like 'mock for savingProductRepository not working'. Include the class, its constructors and dependencies as well as the complete unit test (including the creation of the mocks and what runner you are using). If you do that its less likely that your question gets closed immediately. Also include the full stacktrace of the exception. – second Aug 21 '19 at 19:19

0 Answers0