I have the following code...
@Test
public void wrapSoapTest1() throws TransformerConfigurationException, IOException {
RequestUtil r = new RequestUtil(SAMPLE_REQUEST_BEFORE.getBytes(),"");
URL url = PowerMock.createNiceMock(URL.class);
r.setXslUrl(url);
EasyMock.expect(url.openStream()).andReturn(IOUtils.toInputStream(XSLT, "UTF-8"));
Assert.assertEquals(SAMPLE_REQUEST_AFTER, new String(r.wrapSOAP()));
}
When I run this though I get the following error....
java.lang.AbstractMethodError: java/net/URLStreamHandler.openConnection(Ljava/net/URL;)Ljava/net/URLConnection;
at java.net.URL.openConnection(URL.java:957)
Is there a way to mock a URL and send a custom string as the response?
I have TestNG, PowerMock and EasyMock and only difference is that I had to add @PrepareForTest({ MyTestedClass.class }), in my case MyTestedClass is UrlScreenRequest.
@PrepareForTest({UrlScreenRequest.class})
public class UrlScreenRequestTest extends PowerMockTestCase {
...
@Test
public void testValidatePermission() throws Exception {
URL url=PowerMock.createNiceMock(URL.class);
HttpURLConnection connection = createMock(HttpURLConnection.class);
url.openConnection();
PowerMock.expectLastCall().andReturn(connection);
PowerMock.replayAll(url, connection);
UrlScreenRequest request = new UrlScreenRequest(url);
request.validatePermission();
//validation
}
...
If you use PowerMock
you must ensure that your test case is annotated with @RunWith(PowerMockRunner.class)
. Than you must tell PowerMock
to prepare the URL
class for the test ( @PrepareForTest({ URL.class })
) and you should use PowerMock.expectLastCall()
instead of the EasyMock
methods. At least you must put the mock into the replay mode.
This should work.
@RunWith(PowerMockRunner.class)
@PrepareForTest({ URL.class })
public class SoapTest {
@Test
public void wrapSoapTest1() throws TransformerConfigurationException,
IOException {
RequestUtil r = new RequestUtil(SAMPLE_REQUEST_BEFORE.getBytes(),"");
URL url = PowerMock.createNiceMock(URL.class);
r.setXslUrl(url);
url.openStream();
PowerMock.expectLastCall().andReturn(IOUtils.toInputStream(XSLT, "UTF-8"));
PowerMock.replay(url);
Assert.assertEquals(SAMPLE_REQUEST_AFTER, new String(r.wrapSOAP()));
}
}
My version looks like this...
private URL mockURL() throws IOException{
final URLConnection mockConnection = PowerMock.createMock(URLConnection.class);
InputStream i = IOUtils.toInputStream(XSLT, "UTF-8");
EasyMock.expect(mockConnection.getInputStream()).andReturn(i);
EasyMock.replay(mockConnection);
final URLStreamHandler handler = new URLStreamHandler() {
@Override
protected URLConnection openConnection(final URL arg0)
throws IOException {
return mockConnection;
}
};
return new URL("http://foo.bar", "foo.bar", 80, "", handler);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.