Issue
I'm new to mockito and junit5. I'm trying to test the below function:
public boolean checkFunction(String element) {
CloseableHttpClient client = HttpClients.createDefault();
String uri = "any url im hitting";
HttpPost httpPost = new HttpPost(uri);
String json = element;
StringEntity entity;
try {
entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Authorization", "any token");
CloseableHttpResponse response = client.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());
client.close();
if (responseBody.contains("any string i wanna check"))
return true;
} catch (Exception e) {
return false;
}
return false;
}
I tried the below code but I'm unable to get entire code coverage. Also I don't think this is the right approach.
@Test
public void testCheckFunction() throws Exception {
when(mockClass.checkFunction(Mockito.anyString())).thenReturn(false);
assertEquals(false, mockclass.checkFunction("dummy"));
}
Can anyone help me with this? Thanks!
Solution
First you have to refactor your code for better testability:
public class Checker {
private final CloseableHttpClient client;
public Checker(CloseableHttpClient client) {
this.client = client;
}
public boolean checkFunction(String element) {
String uri = "http://example.com";
HttpPost httpPost = new HttpPost(uri);
String json = element;
StringEntity entity;
try {
entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Authorization", "any token");
CloseableHttpResponse response = client.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());
client.close();
if (responseBody.contains("any string i wanna check"))
return true;
} catch (Exception e) {
return false;
}
return false;
}
}
Note that the dependency (i.e. the thing that has to be mocked in tests) is now injected via the constructor. This way it can easily be replaced by a mock when unit testing this class:
class CheckerTest {
private final CloseableHttpClient clientMock = Mockito.mock(CloseableHttpClient.class);
private final Checker checker = new Checker(clientMock);
@Test
public void testCheckFunction() throws Exception {
when(clientMock.execute(any(HttpPost.class))).thenThrow(new RuntimeException("Oops!"));
assertFalse(checker.checkFunction("dummy"));
}
}
Answered By - slauth