I have this method in my Java application:
public HttpEntity getConfirm(String confirmUrl, String cookie) throws IOException {
LOG.debug("getConfirm triggered");
HttpGet req = null;
try {
HttpClient client = HttpClientBuilder.create().build();
req = new HttpGet(confirmUrl);
req.addHeader("User-Agent", "Apache HTTPClient");
req.addHeader("Cookie", cookie);
HttpResponse res = client.execute(req);
HttpEntity entity = res.getEntity();
int statusLine = res.getStatusLine().getStatusCode();
HttpEntity entity = res.getEntity();
int statusLine = res.getStatusLine().getStatusCode();
String content = EntityUtils.toString(entity);
LOG.info(content + "" + statusLine);
return entity;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (req != null) {
req.releaseConnection();
}
return null;
}
}
This unit test was created to test it:
@Test
public void getConfirmSuccess() throws IOException {
HttpResponse httpResponse = mock(HttpResponse.class);
StatusLine statusLine = mock(StatusLine.class);
when(statusLine.getStatusCode()).thenReturn(200);
when(httpResponse.getStatusLine()).thenReturn(statusLine);
HttpEntity entity = mock(HttpEntity.class);
InputStream stream = new ByteArrayInputStream("{\n\"state\": \"success\",\n\"message\": \"My message.\"\n}".getBytes("UTF-8"));
when(entity.getContent()).thenReturn(stream);
when(httpResponse.getEntity()).thenReturn(mock(HttpEntity.class));
ReissueCertService reissueCertService = new ReissueCertServiceReal();
assertEquals(reissueCertService.reissueCert("http://testurl", "foo"), httpResponse);
}
The test fails as the entity = response.getEntity();
is null so entity never gets assigned a value. I think I need to do a when(entity).thenReturn(...)
but I'm not sure what exactly it is I should be returning. Is this correct and if so what should I return here?
You can do two things in Mock when you write return behavior of a mock object.
If you see here, we returning an mock object of statusLine (who's reference we have), if we do this way we get benefit to choose behavior of statusLine like below:
If you see here, we are returning an mock object of statusLine who's reference we do not hold, so we can not write mock behavior for it which were able to do in first example.