I have three methods,
- void save(String a, String b)
- String getId(String a, Pojo p)
- void update(String a, String b, StringEntity c)
Here are the implementations(not the full implementation),
String getId(String accessToken, Pojo p) {
//Note that the pojo is for formatting the payload for the request, nothing more
HttpResponse response = httpRequestService.makeGetRequest(url, TOKEN_PREFIX, accessToken,
CONTENT_TYPE);
if (response.getStatusLine().getStatusCode() == 200) {
log.debug("Success");
}
//Code for getting the id from the response
return id;
}
void update(String accassToken, String id, StringEntity payload) {
HttpResponse response = httpRequestService.makePutRequest(url + id,
TOKEN_PREFIX, accessToken, CONTENT_TYPE, payload);
if (response.getStatusLine().getStatusCode() == 200) {
log.debug("Success");
}
}
void save(String accessToken, String payload) {
//The getId() is called here
String id = getId(/*arguments*/);
if(id == null) {
log.error("Error");
} else {
//The update() is called here
update(/*arguments*/);
}
}
As mentioned, the getId and update methods are called inside save method and both getId and update methods have HTTP calls.
I have to write a unit test for the save() method. This is what I tried.
//This is an interface with methods to call HTTP requests.
HttpRequestService httpRequestService = Mockito.mock(HttpRequestService.class);
//Constructor injection
ClassWithMethods a = new ClasswithMethods(httpRequestService);
HttpResponse responseGet = Mockito.mock(HttpResponse.class);
StatusLine statusLineGet = Mockito.mock(StatusLine.class);
HttpEntity httpEntity = Mockito.mock(HttpEntity.class);
Mockito.when(responseGet.getStatusLine()).thenReturn(statusLineGet);
Mockito.when(statusLineGet.getStatusCode()).thenReturn(200);
Mockito.when(responseGet.getEntity()).thenReturn(httpEntity);
Mockito.when(httpEntity.getContent()).thenReturn(IOUtils.toInputStream(stream));
Mockito.when(httpRequestService.makeGetRequest(url, TOKEN_PREFIX, accessToken,
CONTENT_TYPE).thenReturn(responseGet);
HttpResponse responsePut = Mockito.mock(HttpResponse.class);
StatusLine statusLinePut = Mockito.mock(StatusLine.class);
Mockito.when(responsePut.getStatusLine()).thenReturn(statusLinePut);
Mockito.when(statusLinePut.getStatusCode()).thenReturn(200);
Mockito.when(httpRequestService.makePutRequest(url + id, TOKEN_PREFIX,
accessToken, CONTENT_TYPE, payloadEntity).thenReturn(responsePut);
a.save(accessToken, payload);
But when testing, the responsePut returns a null. The arguments are also matching.
Problem : How to test this save method which calls two HTTP methods?
This may not be the best way to do this. If there better ways to test a method like this, please suggest.
Thank you
Note that, httpRequestService is an interface with methods for HTTP calls and the constructor injection is used too.