Search code examples
javamockingpowermockapache-commons-io

Mocking apache.commons.io.IOUtils class


I need to mock toByteArray() of apache.commons.io.IOUtils class. I've a code snippet like ths:

PowerMockito.mockStatic(IOUtils.class);
PowerMockito.when(IOUtils.toByteArray(any(InputStream.class))).thenReturn(mockByteArray);

But I'm getting NullPointerException from org.apache.commons.io.IOUtils.copyLarge() function.


Solution

  • It looks like the method is not mocked and the real method is called instead.

    PowerMock uses special test runner that can mock static methods.

    Put @RunWith(PowerMockRunner.class) and @PrepareForTest(IOUtils.class) annotations on your test class.

    See example at docs