I am writing the test case for a method where I am getting
Cannot invoke “com.http.HttpResponse.getStatusCode()" because "response" is null
I have this code
Package …
/* other import */
import com.company.app.http.HttpClient;
import com.company.app.http.HttpResponse;
public class DashboardService {
private final AccountRepository accountRepository;
private final AccountMapper accountMapper;
private final UserService userservice;
private final HttpClient httpClient;
private Dashboard createDashboard(Req req, Dashboard db) throws SomeException {
User user = userService.findByName(req.getId());
HttpResponse<String> response = httpClient.post(User.getUrl() + "/user", getHeaders(),
Req, new TypeReference<>() {
});
if (response.getStatusCode() <= HttpStatus.SC_MULTIPLE_CHOICES) { // here is the error
return db;
} else {
throw new SomeException(response.getStatusMessage() + ": " + response.getResponseText());
}
}
What I am trying to mock in my test case is
HttpResponse<String> mockedResponse = mock(new TypeToken<HttpResponse<String>>() {}.getRawType());
when(httpClient.post(anyString(), anyList(), any(), any(TypeReference.class))).thenReturn(mockedResponse);
For additional Info this is httpclient.post
@Log4j2
@Component
public class HttpClient {
@Autowired
public HttpClient() {
}
public <T> HttpResponse<T> post(String url, List<Header> httpHeaders, Object data,
TypeReference<T> typeReference)
throws IdentityException {
CloseableHttpClient client = getClient();
try {
HttpPost postRequest = new HttpPost(url);
Header[] itemsArray = new Header[httpHeaders.size()];
itemsArray = httpHeaders.toArray(itemsArray);
postRequest.setHeaders(itemsArray);
postRequest.setEntity(prepareBody(data));
org.apache.http.HttpResponse res;
res = client.execute(postRequest);
return new HttpResponse<>(res, typeReference);
} catch (IOException e) {
throw new IdentityException(e);
} finally {
if (client != null) {
closeConnection(client);
}
}
}
public synchronized CloseableHttpClient getClient() {
RequestConfig config = RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD)
.setSocketTimeout(10 * 60 * 1000)
.setConnectionRequestTimeout(60 * 1000)
.setConnectTimeout(2 * 60 * 1000)
.build();
return HttpClients.custom().setDefaultRequestConfig(config).build();
}
}
HttpResponse
public HttpResponse(org.apache.http.HttpResponse response, TypeReference<T> typeReference)
throws IOException {
this.statusCode = response.getStatusLine().getStatusCode();
this.statusMessage = response.getStatusLine().getReasonPhrase();
if (response.getEntity() != null)
this.responseText = EntityUtils.toString(response.getEntity());
log.info("Http Response details: Code - " + statusCode + ", Message - " + statusMessage);
log.info("Response entityString: " + StringUtils.abbreviate(responseText, 500));
setParsedResponse(typeReference);
}
What I am trying is also not working. Can anyone suggest me what should I try to Mock this. So that I can get off from response is null error and can proceed further.