I created a mock HttpsURLConnection
based on an StackExchange answer:
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 ...
}
}
However, when I use it, I'm seeing a cast exception:
java.lang.ClassCastException: sun.net.www.protocol.https.HttpsURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection
The problem lies in this code:
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();
However, when I look at the source code, I see that sun.net.www.protocol.https.HttpsURLConnectionImpl
implements javax.net.ssl.HttpsURLConnection
Any suggestions on how to remedy this problem?