Mocking getResourceAsStream

3,310 views
Skip to first unread message

Thomas

unread,
Feb 24, 2011, 11:39:24 AM2/24/11
to PowerMock
First of all: Thank you for this great tool. It really helps me to
build much more meaningful tests.
Currently I am stuck with trying to mock loading a resource. I have a
class, which looks like the following:

class ClassUnderTest {
public XYZ loadResource(someParameters) {
Stream stream;
if (someCondition) {
stream = getClass().getResourceAsStream("/fileA");
} else {
stream = getClass().getResourceAsStream("/fileB");
}
//... do something and return a value
}

Now, I would like to test, that the right resource is loaded (I
suppose, it makes no difference, whether I use getResourceAsStream or
just getResource). I tried the following:

@RunWith(PowerMockRunner.class)
@PrepareForTest({Class.class, ClassUnderTest.class, MyTest.class})
class MyTest {
@Test
public void testLoadResource() {
//...
Class<ClassUnderTest> mockClass =
PowerMock.createMock(Class.class);

PowerMock.stub(ClassUnderTest.class.getMethod("getClass")).toReturn(mockedClass);
expect(mockClass.getResourceAsStream("/
fileA")).andReturn(someFakeStream);
//...
}
}

This gives me an IllegalAccessError in createMock. Am I right, that
the problem is, that Class cannot be instantiated and therefore
PowerMock cannot create a mock of it? I also tried adding
PowerMock.suppress(PowerMock.constructor(Class.class)); before
creating the mock, but this did not change anything.
Is there a solution or a workaround for this problem? (I have to
verify the parameters passed to getResourceAsStream - otherwise I
could simply use PowerMock.stub(...)).
Thank you in advance for any responses.

Kind regards,
Thomas Milde

Johan Haleby

unread,
Feb 25, 2011, 1:49:17 AM2/25/11
to powe...@googlegroups.com
Hi, 

I think that in cases like this I'd prefer to actually load a test-version of of the file instead. E.g. refactor your code and inject/set the file to the instance so that you can easily change it when performing your test.

getClass() is not mockable by default in PowerMock, try setting MockGateway.MOCK_GET_CLASS_METHOD = true before you run your test. 

/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.


Reply all
Reply to author
Forward
0 new messages