Search code examples
javajunit

How to mock HttpClient.newHttpClient() in Junit


 public String sendAPICall(String portalApiUrl, String reviewAppsAuthKey) {

    try {
        HttpRequest request = HttpRequest.newBuilder()
                .uri(new URI(portalApiUrl + CHECK_ORG_ATT_EXP))
                .setHeader(AUTH_REVIEW_API_KEY, reviewAppsAuthKey)
                .setHeader(CONTENT_TYPE, APPLICATION_JSON)
                .GET()
                .build();

        HttpClient httpClient = HttpClient.newHttpClient();

        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() == HttpStatus.OK.value()) {
            LOGGER.info(API_SUCCESS);
            return API_SUCCESS;
        }
    } catch (URISyntaxException e) {
        LOGGER.error(API_FAIL_URI, e.getMessage());
    } catch (InterruptedException e) {
        LOGGER.error(API_FAIL_INTER, e.getMessage());
    } catch (IOException e) {
        LOGGER.error(API_FAIL_IO, e.getMessage());
    }
    return API_FAILURE;

}

}

Junit :

@Test
public void sendAPICallTest() throws IOException, InterruptedException {

    Checkorg test = getCheckOrg();
    String portalApiUrl = JUNIT_PORTAL_URL;
    String reviewAppsAuthKey = JUNIT_AUTH_KEY;
   String message = test.sendAPICall(portalApiUrl, reviewAppsAuthKey);
    assertEquals(Checkorg.API_SUCCESS, message);
}

How to mock the HTTP Client in Test Class.

Thank you


Solution

  • As per your comment:

    how can we test this method for success if we can't mock

    you can use spy for that :

    @Test
    public void sendAPICallTest() throws IOException, InterruptedException {
    
        Checkorg test = getCheckOrg();
        String portalApiUrl = JUNIT_PORTAL_URL;
        String reviewAppsAuthKey = JUNIT_AUTH_KEY;
        Checkorg mockedTest = Mockito.spy(test);
        Mockito.when(mockedTest.sendAPICall(portalApiUrl,reviewAppsAuthKey)).thenReturn("API Call Success");
        String message = mockedTest.sendAPICall(portalApiUrl, reviewAppsAuthKey);
        assertEquals(Checkorg.API_SUCCESS, message);
    }
    

    This can be a quick workaround if HttpClient mocking is not feasible.