powermock 静态方法mock
所属分类 unit-test
浏览量 628
HttpClientUtil 静态方法 doGet mock
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({HttpClientUtil.class})
//@PowerMockIgnore({"javax.script.*", "javax.management.*", "org.w3c.dom.*", "org.apache.log4j.*", "org.xml.sax.*", "javax.xml.*"})
@PowerMockIgnore({"javax.net.ssl.*"})
public class HttpClientUtilMockTest {
@Test
public void doGetTest() throws Exception{
PowerMockito.mockStatic(HttpClientUtil.class);
PowerMockito.when(HttpClientUtil.doGet(Mockito.anyString())).thenReturn("666");
String url = "http://codefun007.xyz/pv.htm";
String pv = HttpClientUtil.doGet(url);
System.out.println(pv);
}
}
注意 一定要加 @PowerMockIgnore({"javax.net.ssl.*"})
默认使用自己的classLoader去loader所有的class,除 system class(java.lang等目录下的class),
使用 powermockIgnore 声明的class,pwoermock 不会加载
否则报错
Caused by: org.apache.http.ssl.SSLInitializationException: class configured for SSLContext: sun.security.ssl.SSLContextImpl$TLSContext not a SSLContext
Caused by: java.security.NoSuchAlgorithmException: class configured for SSLContext: sun.security.ssl.SSLContextImpl$TLSContext not a SSLContext
完整代码
https://gitee.com/dyyx/hellocode/blob/master/demo/springboot1.5.4demo/src/test/java/dyyx/demo/util/HttpClientUtilMockTest.java
上一篇
下一篇
zookeeper单机安装
Spring ProxyFactory 和 方法拦截器 MethodInterceptor
Spring AOP @Aspect
mockito 实例
Mocktio 指南
Mockito mock 和 spy 区别