4

My connection works fine with:

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

And I've a test with @RunWith(PowerMockRunner.class) and @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(...);

With OK.

Now, I want to close connection with HttpURLConnection and disconnect() method. This works fine in code:

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

But in test can't be casted:

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

How can I support cast in test to disconnect this conection with PowerMockito?

Thanks.

Community
  • 1
  • 1
Corporativo
  • 185
  • 1
  • 2
  • 11

1 Answers1

1

Not tested, but instead of:

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

use:

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

Otherwise your mocked class is of the wrong type.

ewramner
  • 5,810
  • 2
  • 17
  • 33