how to mock a URL connection
You can mock new Url instance with
whenNew(URL.class)..
Make sure you return a previously created mock object from that whenNew call.
URL mockUrl = Mockito.mock(URL.class);
whenNew(URL.class).....thenReturn(mockUrl );
Then you can add behavior to your mock as you want.
Although this thread has some good suggestion, but if any of you is not interested to use those third-party libraries here is a quick solution.
public class MockHttpURLConnection extends HttpURLConnection {
private int responseCode;
private URL url;
private InputStream inputStream;
public MockHttpURLConnection(URL u){
super(null);
this.url=u;
}
@Override
public int getResponseCode() {
return responseCode;
}
public void setResponseCode(int responseCode) {
this.responseCode = responseCode;
}
@Override
public URL getURL() {
return url;
}
public void setUrl(URL url) {
this.url = url;
}
@Override
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public void disconnect() {
}
@Override
public boolean usingProxy() {
return false;
}
@Override
public void connect() throws IOException {
}
}
And, this how you can set the desired behaviour
MockHttpURLConnection httpURLConnection=new MockHttpURLConnection(new URL("my_fancy_url"));
InputStream stream=new ByteArrayInputStream(json_response.getBytes());
httpURLConnection.setInputStream(stream);
httpURLConnection.setResponseCode(200);
Note: It just mock 3 methods from HttpUrlConnection
and if you are using more method you need to make sure those are mock as well.
Found the solution. First mock the URL class, then Mock the HttpURLConnection and when url.openconnection() is called, return this mocked HttpURLConnection object and finally set its response code to 200. Heres the code:
@Test
public void function() throws Exception{
RuleEngineUtil r = new RuleEngineUtil();
URL u = PowerMockito.mock(URL.class);
String url = "http://www.sdsgle.com";
PowerMockito.whenNew(URL.class).withArguments(url).thenReturn(u);
HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class);
PowerMockito.when(u.openConnection()).thenReturn(huc);
PowerMockito.when(huc.getResponseCode()).thenReturn(200);
assertTrue(r.isUrlAccessible(url));
}