'Apache Http Client Unit Test Issue | HttpResponseProxy{HTTP/1.1 406 Not Acceptable

While unit testing my code of posting payload to an endpoint I am getting exception like HttpResponseProxy{HTTP/1.1 406 Not Acceptable}

HttpClient httpClient = mock(HttpClient.class);
HttpResponse httpResponse = mock(HttpResponse.class);
StatusLine statusLine = mock(StatusLine.class);
doReturn(HttpURLConnection.HTTP_CREATED).when(statusLine).getStatusCode();
doReturn(httpResponse).when(httpClient).execute(any());
HttpResponse response = service.postData("payload to be sent");
Assertions.assertNotNull(response);
Assertions.assertNotNull(response.getStatusLine().getStatusCode());
Assertions.assertNotNull(response.getEntity());
Assertions.assertNotNull(response.getHeaders("Authorization"));
Assertions.assertNotNull(response.getHeaders("Content-type"));

Actual Code -

try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

    HttpPost httppost = new HttpPost(endpoint);

    httppost.setHeader("Authorization", "Bearer " + token);
    httppost.setEntity(payloadString);
    httppost.setHeader("Content-type", "application/json");

    httpresponse = httpclient.execute(httppost);

    responseCode = httpresponse.getStatusLine().getStatusCode();

}
return responseCode;

Please guide where I am going wrong and the right way to do this.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source