I have this method:
public void updateService(JSONObject json, String url) throws IOException {
PrintStream log = this.getLogger();
CloseableHttpClient httpClient = null;
httpClient = this.getCloseableHttpClient();
log.println("Sending data to " + url);
HttpPut request = new HttpPut(url);
StringEntity params = new StringEntity(json.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
httpClient.execute(request);
log.println("Sending report succeeded");
httpClient.close();
}
My test then does this:
@Test
public void updateServiceCloseException() {
RegistryTask task = new RegistryTask(false, null);
RegistryTask spy = spy(task);
CloseableHttpClient client = HttpClientBuilder.create().build();
CloseableHttpClient clientSpy = spy(client);
String url = "http://www.example.com/api/service/testo";
String message = "Execute failure";
JSONObject json = new JSONObject();
json.put("name", "Bob");
json.put("key", "testo");
try {
doReturn(clientSpy).when(spy).getCloseableHttpClient();
// Make sure no http request is actually sent
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
IOException exception = new IOException(message);
doReturn(response).when(clientSpy).execute(any(HttpPut.class));
doThrow(exception).when(clientSpy).close();
spy.updateService(json, url);
} catch (IOException e) {
failWithTrace(e);
// assertEquals(message, e.getMessage());
return;
} catch (Exception e) {
failWithTrace(e);
// assertEquals(message, e.getMessage());
return;
}
fail("Exception not thrown");
}
For some reason doThrow(exception).when(clientSpy).close();
is saying Checked exception is invalid for this method!
. But considering my method has throws IOException
and close
itself throws IOException
, I am completely confused about getting this JUnit exception.
Update
I tried updating the doReturn
to when(clientSpy.execute(any(HttpPut.class))).thenReturn(response);
. The new exception is java.lang.AssertionError: java.lang.IllegalArgumentException: HTTP request may not be null
. Not sure why using any
would count as null
in this case. This question actually shows I should use doReturn
since it always work vs thenReturn
not working in all cases... Mockito - difference between doReturn() and when()