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