java – ClassCastException断开与PowerMockito的URLConnection连接的HttpURLConnection

我的连接工作正常:

URLConnectionFactory hadoopConnectionFactory = URLConnectionFactory.newDefaultURLConnectionFactory(cfg);
String url = "...";
URLConnection urc = hadoopConnectionFactory.openConnection(new URL(url));
urc.connect();
// Do something with urc.getInputStream()

我使用@RunWith(PowerMockRunner.class)和@PrepareForTest({URLConnectionFactory.class})进行了测试:

PowerMockito.mockStatic(URLConnectionFactory.class);
URLConnectionFactory hadoopConnectionFactory = PowerMockito.mock(URLConnectionFactory.class);
PowerMockito.when(URLConnectionFactory.newDefaultURLConnectionFactory(anyObject())).thenReturn(hadoopConnectionFactory);
URLConnection urc = PowerMockito.mock(URLConnection.class);
PowerMockito.when(hadoopConnectionFactory.openConnection(anyObject())).thenReturn(urc);
PowerMockito.when(urc.getInputStream()).thenReturn(...);

好的.

现在,我想关闭与HttpURLConnection和disconnect()方法的连接.这在代码中工作正常:

HttpURLConnection conn = (HttpURLConnection) urc;
conn.disconnect();

但在测试中无法投入:

java.lang.ClassCastException: $java.net.URLConnection$$EnhancerByMockitoWithCGLIB$$6fcf4cc9 cannot be cast to java.net.HttpURLConnection

如何支持测试中的转换以断开与PowerMockito的连接?

谢谢.

解决方法:

未经测试,但代替:

URLConnection urc = PowerMockito.mock(URLConnection.class);

使用:

URLConnection urc = PowerMockito.mock(HttpURLConnection.class);

否则你的模拟类是错误的类型.

上一篇:java – 验证CXF HttpAsyncClient使用use.async.http.conduit上下文属性


下一篇:Android无法使用HttpURLConnection发送GET请求