How to cover method inside arrayList in mockito junits

Viewed 33

I am trying to cover below main class if (!Utility.isEmpty(errors)) block code coverage and i tried below code for adding errors in array List inside client class but still array showing as empty can some one help me to solve this issue.

Main class

public void processDiohShippingMethod(ShippingMethodRequest request) {
        List<ResolvableErrorEnum> errors = new ArrayList<>();
        checkoutRestClient.updateShippingMethod(request, errors);
        if (!Utility.isEmpty(errors)) {
            logger.info("ProcessDiohShippingMethod: Shipping method update failure  from {} -> {}. Reverting. ",
                    existingSm, request.getShippingMethodType());
            if (existingShippingMethod != null && Constants.RTG_ENJOY.equalsIgnoreCase(existingSm)) {
                request.setStartTime(existingShippingMethod.getDropOffShippingInfo().getStartTime());
                request.setEndTime(existingShippingMethod.getDropOffShippingInfo().getEndTime());
                request.setScheduleType(existingShippingMethod.getDropOffShippingInfo().getCustomerScheduleType());
            }
        }
    }

Client

public void updateShippingMethod(ShippingMethodRequest request, List<ResolvableErrorEnum> errors) {
    String url = Utils.formatHttpUrl(url, Cart_Request);
    try {
        HttpEntity<?> entity = new HttpEntity<>(request);
        JsonNode jsonNode = restTemplate.postForObject(url, entity, JsonNode.class);
        if (!jsonNode.has(Constants.CONTENT)
                || !jsonNode.path(Constants.CONTENT).path(Constants.ERRORS).isMissingNode()) {
            errors.add(ErrorMessages.SM_ERR_01);
            return;
        }
    } catch (HttpClientErrorException e) {
        errors.add(ErrorMessages.SM_ERR_01);
    } catch (HttpServerErrorException e) {
        errors.add(ErrorMessages.SM_ERR_01);
    }
}

Test

@Test
    public void test_processMethod() throws Exception {
        Request req = new Request();
        HttpEntity<?> entity = new HttpEntity<>(req);
        String jsonResponse = "{\"error\":{\"errorId\":\"1234\",\"message\":\"error message\"}},\"status\":\"success\"}}";
        ObjectMapper mapper = new ObjectMapper();
        JsonNode actualObj = mapper.readTree(jsonResponse);
        when(restTemplate.postForObject("url", entity, JsonNode.class)).thenReturn(actualObj);

        ShippingMethodResponse response = helper.processDiohShippingMethod(req);
    }
1 Answers

Since you didn't post the whole test code this is just an educated guess, but the most probable cause is that your helper object (the one from the test method) uses a different instance, but not the one you mocked (since I can't see any code in the test, that would set the client).

So a solution could look like this:

@Test
public void test_processMethod() throws Exception {
    Request req = new Request();
    HttpEntity<?> entity = new HttpEntity<>(req);
    String jsonResponse = "{\"error\":{\"errorId\":\"1234\",\"message\":\"error message\"}},\"status\":\"success\"}}";
    ObjectMapper mapper = new ObjectMapper();
    JsonNode actualObj = mapper.readTree(jsonResponse);
    when(restTemplate.postForObject("url", entity, JsonNode.class)).thenReturn(actualObj);

    //get this mocked object into the helper object somehow
    //otherwhise the mocked method will never be called
    helper.setClient(restTemplate);

    ShippingMethodResponse response = helper.processDiohShippingMethod(req);
}

You probably assumed the mocking call when(restTemplate.postForObject(...))... to mock the method for all objects of this class. But it will just create a decorator- / wrapper-object arround the object. So you've got to make shure that you call the mocked method on the mocked object, but not on any other object.

Related