Mocking a URL in Java

前端 未结 10 1697
臣服心动
臣服心动 2020-12-14 08:16

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 beca

10条回答
  •  庸人自扰
    2020-12-14 08:49

    I went with the following:

    public static URL getMockUrl(final String filename) throws IOException {
        final File file = new File("testdata/" + filename);
        assertTrue("Mock HTML File " + filename + " not found", file.exists());
        final URLConnection mockConnection = Mockito.mock(URLConnection.class);
        given(mockConnection.getInputStream()).willReturn(
                new FileInputStream(file));
    
        final URLStreamHandler handler = new URLStreamHandler() {
    
            @Override
            protected URLConnection openConnection(final URL arg0)
                    throws IOException {
                return mockConnection;
            }
        };
        final URL url = new URL("http://foo.bar", "foo.bar", 80, "", handler);
        return url;
    }
    

    This gives me a real URL object that contains my mock data.

提交回复
热议问题