我创建了一个HttpsURLConnection
基于StackExchange 答案的模拟:
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
...
@RunWith(PowerMockRunner.class)
public class DialogTest {
public void mockHttpsUrlConnectionExample() throws Exception
{
URL mockUrl = PowerMockito.mock(URL.class);
PowerMockito.whenNew(URL.class).withAnyArguments().thenReturn(mockUrl);
HttpsURLConnection mockUrlConnection = PowerMockito.mock(HttpsURLConnection.class);
PowerMockito.when(mockUrl.openConnection()).thenReturn(mockUrlConnection);
PowerMockito.when(mockUrlConnection.getResponseCode()).thenReturn(200);
// Create and call my objects ...
}
}
但是,当我使用它时,我看到了一个强制转换异常:
java.lang.ClassCastException: sun.net.www.protocol.https.HttpsURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection
问题在于这段代码:
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
...
private Boolean sendRequest(String endpoint, JSONObject requestData, Boolean throwOnAuthException) throws JSONException, IOException {
this.responseData = null;
try {
String serviceURI = getServiceURI();
String dialogUri = String.format("%s%s", serviceURI, endpoint);
URL url = new URL(dialogUri);
// Exception source is this cast
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
但是,当我查看源代码时,我看到sun.net.www.protocol.https.HttpsURLConnectionImpl
实现javax.net.ssl.HttpsURLConnection
有关如何解决此问题的任何建议?