简体   繁体   English

使用Powermockito模拟最终类的本地对象创建

[英]Mocking local object creation of a final class using Powermockito

I am trying to mock a final class object creation using PowerMockito. 我正在尝试使用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

在此处输入图片说明

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. 您还需要准备Sample类。 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. 除非您准备Sample类,否则Powermock不知道它应该代理该类,这意味着它不会干扰该类内部发生的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM