Search code examples
javaunit-testingpowermockito

Mocking local object creation of a final class using Powermockito


I am trying to mock a final class object creation using PowerMockito. But it is not taking into consideration of the mock object and creating actual object as seen in the output and debug screenshot.

What could be missing here.

Please clarify.

Class

import java.net.MalformedURLException;
import java.net.URL;

public class Sample {

public void m1(String input) throws IOException {
    URL url = new URL(input);
    URLConnection connection = url.openConnection();
    System.out.println(url);
    System.out.println(connection);
}

}

Test Class

import java.net.URL;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ URL.class })
public class SampleTest {
@Test
public void testM1() throws Exception {
    String input = "http://www.example.com";

    URL url = PowerMockito.mock(URL.class);
    PowerMockito.whenNew(URL.class).withAnyArguments().thenReturn(url);

    Sample sample = new Sample();
    sample.m1(input);
}
}

Output

http://www.example.com
sun.net.www.protocol.http.HttpURLConnection:http://www.example.com

enter image description here


Solution

  • There is nothing wrong in your Test per se. Only thing you are missing is this

    @PrepareForTest({ URL.class , Sample.class})
    

    You need to prepare your Sample class also. Unless you prepare Sample class, Powermock doesn't know it should proxy that class, which mean it doesn't interfere with what happens inside that.