Ashley
Ashley

Reputation: 491

Mocking URL objects in java without PowerMockito

Is it possible to mock HttpURLConnection & URL object. My constraint is that I'm not suppose to use PowerMockito. I can use Mockito but Mockito says URL cannot be mocked since it is final class.

public static int getResponseCode(String urlString)
        throws MalformedURLException, IOException
{
    URL u = new URL(urlString);
    HttpURLConnection huc = (HttpURLConnection)u.openConnection();
    huc.setRequestMethod("GET");
    huc.connect();
    return huc.getResponseCode();
}

Upvotes: 0

Views: 1604

Answers (2)

mdewit
mdewit

Reputation: 2036

You can create a wrapper class that wraps a URL and then by default delegates calls to its methods to an actual URL implementation.

Eg:

public class URLWrapper {
    private URL url;

    public URLWrapper(String urlString) {
        this.url = new URL(urlString);
    }

    public HttpURLConnection openConnection() {
        return this.url.openConnection();
    }

    //etc
}

Now use URLWrapper in your class instead of using URL directly. URLWrapper can now easily be mocked.

Upvotes: 1

suulisin
suulisin

Reputation: 1434

please try with this

final URLConnection mockUrlCon = mock(URLConnection.class);

ByteArrayInputStream is = new ByteArrayInputStream(
        "<myList></myList>".getBytes("UTF-8"));
doReturn(is).when(mockUrlCon).getInputStream();

//make getLastModified() return first 10, then 11
when(mockUrlCon.getLastModified()).thenReturn((Long)10L, (Long)11L);

URLStreamHandler stubUrlHandler = new URLStreamHandler() {
    @Override
     protected URLConnection openConnection(URL u) throws IOException {
        return mockUrlCon;
     }            
};
URL url = new URL("foo", "bar", 99, "/foobar", stubUrlHandler);
doReturn(url).when(mockClassloader).getResource("pseudo-xml-path");

Upvotes: 0

Related Questions