有没有任何方法可以将PowerMock与rest-assed一起使用,因为当我尝试使用rest-assered测试RESTful API时。
我想要PowerMock一个静态调用。
操作代码:
@POST
@Produces("application/json")
@Consumes(MediaType.APPLICATION_JSON)
public Response createEntity(@Context HttpHeaders hh, String body) {
. . .
String sec = MDI.check(Some_string, ..., ...);
if (sec == null) throw ...
return Response....
}
测试:
@RunWith(PowerMockRunner.class)
@PrepareForTest(MDI.class)
public class createSOTest {
@Test
public void testStatic() {
mockStatic(MDI.class);
expect(MDI.check(Some_string, ..., ...).andReturn(Some_String);
replay(MDI.class)
given().
contentType(ContentType.JSON).
header("SomeHeader", "something").
body(root).
when().
post("/").
then().
statusCode(...);
}
}
问题是,当测试尝试运行rest-assured
代码(given()....
)时,我获得了一个异常:
org.apache.http.conn.ssl.SSLInitializationException: class configured for SSLContext: sun.security.ssl.SSLContextImpl$TLS10Context not a SSLContext
at org.apache.http.conn.ssl.SSLContexts.createDefault(SSLContexts.java:58)
at org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory(SSLSocketFactory.java:162)
at org.apache.http.impl.conn.SchemeRegistryFactory.createDefault(SchemeRegistryFactory.java:52)
at org.apache.http.impl.client.AbstractHttpClient.createClientConnectionManager(AbstractHttpClient.java:305)
at org.apache.http.impl.client.AbstractHttpClient.getConnectionManager(AbstractHttpClient.java:465)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
at org.codehaus.groovy.runtime.metaclass.MethodMetaProperty$GetBeanMethodMetaProperty.getProperty(MethodMetaProperty.java:73)
at org.codehaus.groovy.runtime.callsite.GetEffectivePojoPropertySite.getProperty(GetEffectivePojoPropertySite.java:61)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:227)
at com.jayway.restassured.internal.RequestSpecificationImpl.applyProxySettings(RequestSpecificationImpl.groovy:1794)
这似乎是PowerMockRunner.class
的问题。
我遇到了同样的问题,并在这个博客上找到了解决方案:
这与SSLOntext从上游类加载器加载内容有关,这是Power Mock在运行测试时使用的类加载器。
解决方案:在测试类顶部使用@PowerMockIgnore注释:
@PowerMockIgnore("javax.net.ssl.*")
@PowerMockIgnore({"javax.management.*", "org.apache.http.conn.ssl.*", "com.amazonaws.http.conn.ssl.*", "javax.net.ssl.*"})
这看起来不像是一个powermock问题。通过暂时删除测试代码中的静态依赖关系来缩小它的范围——将其截断,这样它只返回任何内容。不要嘲笑我,再试一次。您可能会得到相同的错误,在这种情况下,您可以调查该错误。