I'm trying to use PowerMockito to make fun of creating a java.net.URL class in my code that I'm testing. Basically, I want a real HTTP request not to occur, and instead: 1) check the data when the request is executed and 2) return my own test data back to the mocked reaction. This is what I am trying:
@RunWith(PowerMockRunner.class) @PrepareForTest({ URL.class, MockedHttpConnection.class }) public class Test { URL mockedURL = PowerMockito.mock(URL.class); MockedHttpConnection mockedConnection = PowerMockito.mock(MockedHttpConnection.class); ... PowerMockito.whenNew(URL.class).withParameterTypes(String.class).withArguments("MyURLString").thenReturn(mockedURL); PowerMockito.when(mockedURL.openConnection()).thenReturn(mockedConnection); ... }
The code I want to check is as follows:
URL wlInvokeUrl = new URL(wlInvokeUrlString); connection = (HttpURLConnection) wlInvokeUrl.openConnection();
Earlier in my test case, I made fun of wlInvokeUrlString to match "MyURLString". I also tried using various other forms of the whenNew line, trying to introduce a layout. No matter what I try, it never intercepts the constructor. All I want to do is to βcatchβ the openConnection () call and return its mocked HTTP connection instead of the real one.
I ridiculed the other classes before this in the same script, and they work as expected. Either I need a second pair of eyes (maybe true), or something unique about the URL class. I noticed that if I use "whenNew (URL.class) .withAnyArguments ()" and change "thenReturn" to "thenAnswer", I can get it to run. The only problem is that I never get the url of my code. What I see is a constructor call with 3 arguments for URL.class with all zeros for the parameters. Could this class be from the Java runtime and loaded by a test runner? Any help is greatly appreciated.
source share