'How to mock URL connection class using powerMock

This is my main method for which I want to write Junit

private HttpURLConnection createRedirectURL(String childNode) throws IOException {
        URL url = new URL(childNode);
        HttpURLConnection ulrConnection = (HttpURLConnection) url.openConnection();
        ulrConnection.setDoOutput(true);
        ulrConnection.setDoInput(true);
        return ulrConnection;
    }

And this is my test case for URL Connection class

private void createMockInteropNode() throws Exception {
URL url = PowerMock.createMock(URL.class);
        
        PowerMock.expectNew(URL.class, EasyMock.anyString()).andReturn(url);
        HttpURLConnection connection = EasyMock.createMock(HttpURLConnection.class);

        EasyMock.expect(url.openConnection()).andReturn(connection);
        EasyMock.replay(connection);
        PowerMock.replayAll();
    }
}

In starting of testClass I have added URL.class in @PrepareForTest but still not able to mock URL connection. I am using

  • JDK 11 version, PowerMock-api-easymock-2.0.2.jar, Junit-4.12.jar.

Am I on the right track? Can anyone help me in implementing this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source