Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a URL in Java

Tags:

java

url

mocking

We have a URL object in one of our Java classes that we want to mock, but it's a final class so we cannot. We do not want to go a level above, and mock the InputStream because that will still leave us with untested code (we have draconian test coverage standards).

I've tried jMockIt's reflective powers but we work on Macs and there are problems with the Java agent handler that I haven't been able to resolve.

So are there any solutions that do not involve using real URLs in the junit test?

like image 990
bowsie Avatar asked Sep 02 '25 05:09

bowsie


1 Answers

Like Rob said, if what you want is to mock the connection returned from the URL, you can extend URLStreamHandler. For instance, with mockito:

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");
like image 93
Artefacto Avatar answered Sep 04 '25 20:09

Artefacto