this is the method for which junit is written
public boolean isSelfServicePortalServerAvailable(String crmEndPoint) {
boolean isServerAvailable = false;
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(crmEndPoint);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
isServerAvailable = true;
connection.disconnect();
} catch (MalformedURLException e) {
log.error(e.getMessage());
} catch (IOException e) {
log.error(e.getMessage());
}
return isServerAvailable;
}
This is the test case wriiten
@Mock
private URL mockUrl;
@Mock
private HttpURLConnection mockConnection;
@Mock
private ISelfServiceDao selfServiceDao;
@Mock
private RestTemplate restTemplate;
@InjectMocks
private SelfServiceCoreClaimImpl selfServiceCoreClaimImpl = new SelfServiceCoreClaimImpl(restTemplate);
@Test
public void testIsSelfServicePortalServerAvailable_Success() throws IOException {
when(mockUrl.openConnection()).thenReturn(mockConnection);
doNothing().when(mockConnection).connect();
doNothing().when(mockConnection).disconnect();
boolean result = selfServiceCoreClaimImpl.isSelfServicePortalServerAvailable("http://test-url.com");
assertTrue(result);
}
errors org.mockito.exceptions.misusing.UnnecessaryStubbingException: Unnecessary stubbings detected. Clean & maintainable test code requires zero unnecessary code. Following stubbings are unnecessary (click to navigate to relevant line of code):
Not calling mock ... can someone help me on this
I would try:
public boolean isSelfServicePortalServerAvailable(String crmEndPoint) {
boolean isServerAvailable = false;
try {
HttpURLConnection connection = getHttpURLConnection(crmEndPoint);
connection.connect();
isServerAvailable = true;
connection.disconnect();
} catch (MalformedURLException e) {
log.error(e.getMessage());
} catch (IOException e) {
log.error(e.getMessage());
}
return isServerAvailable;
}
private HttpURLConnection getHttpURLConnection(String crmEndPoint) throws IOException {
URL url = new URL(crmEndPoint);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
return connection;
}
And then test
@Mock
private HttpURLConnection mockConnection;
@Mock
private ISelfServiceDao selfServiceDao;
@Mock
private RestTemplate restTemplate;
@InjectMocks
@Spy
private SelfServiceCoreClaimImpl selfServiceCoreClaimImpl;
@Test
public void testIsSelfServicePortalServerAvailable_Success() throws IOException {
String crmEndPoint = "http://test-url.com";
doReturn(mockConnection).when(selfServiceCoreClaimImpl).getHttpURLConnection(crmEndPoint);
doNothing().when(mockConnection).connect();
doNothing().when(mockConnection).disconnect();
boolean result = selfServiceCoreClaimImpl.isSelfServicePortalServerAvailable(crmEndPoint);
assertTrue(result);
}