Problems PowerMocking URL with JUnit 4.8.1 and PowerMock 3.7.1

633 views
Skip to first unread message

remotenemesis

unread,
Mar 29, 2010, 3:56:39 PM3/29/10
to PowerMock
I'm having trouble PowerMocking a URl in a test case. I end up getting
a NullPointerException inside java.net.URL.openConnection() which is
being called from java.net.URL.openStream() which is the actual method
I am calling in the URLThing::do() below. It looks like URL is not
being mocked.

Any advice?

Thanks!

Andy

import static org.powermock.api.easymock.PowerMock.expectLastCall;
import static org.powermock.api.easymock.PowerMock.createMock;
import static org.powermock.api.easymock.PowerMock.replay;
import static org.powermock.api.easymock.PowerMock.verify;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@PrepareForTest(URL.class)
@RunWith(PowerMockRunner.class)
public class URLThingTest {

private URL url;

private InputStream inputStream;

@Before
public void setUp() throws MalformedURLException {
url = createMock(URL.class);
inputStream = createMock(InputStream.class);
}

@Test
public void theBadTest() throws IOException {

url.openStream();
expectLastCall().andReturn(inputStream);

inputStream.close();
expectLastCall().once();

replay(url, inputStream);

final String digest = new URLThing().do(url);

verify(url, inputStream);
}

}

Johan Haleby

unread,
Mar 29, 2010, 4:26:17 PM3/29/10
to powe...@googlegroups.com
Hi,

The reason is that URL is a system class and cannot be byte-code manipulated. System classes must be dealt with in a special way, i.e. you prepare the class using the system class and not the system class itself. In your case you should probably prepare URLThing.class for test instead of URL.class. See documentation.

/Johan


--
You received this message because you are subscribed to the Google Groups "PowerMock" group.
To post to this group, send email to powe...@googlegroups.com.
To unsubscribe from this group, send email to powermock+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/powermock?hl=en.


Andy Hull

unread,
Mar 29, 2010, 4:40:44 PM3/29/10
to powe...@googlegroups.com
Ah I understand. Works perfectly... (as if by magic!). Thanks for your help.

-Andy

Johan Haleby

unread,
Mar 30, 2010, 2:12:53 AM3/30/10
to powe...@googlegroups.com
Great :)
Reply all
Reply to author
Forward
0 new messages