I have an image loader class and i need to test some static methods in it. Since Mockito does not support static methods i switched to Power Mockito. But the static method i am
Short answer you can't. Here from the FAQ:
What are the limitations of Mockito
- Cannot mock final classes
- Cannot mock static methods
- Cannot mock final methods - their real behavior is executed without any exception. Mockito cannot warn you about mocking final methods so be vigilant.
Further information about this limitation:
Can I mock static methods?
No. Mockito prefers object orientation and dependency injection over static, procedural code that is hard to understand & change. If you deal with scary legacy code you can use JMockit or Powermock to mock static methods.
If you want to use PowerMock try like this:
@RunWith(PowerMockRunner.class)
@PrepareForTest( { Base64.class })
public class YourTestCase {
@Test
public void testStatic() {
mockStatic(Base64.class);
when(Base64.encodeToString(argument)).thenReturn("expected result");
}
}
EDIT:
In Mockito 2 it's now possible to mock final Class and final Method. It's an opt-in option. You need to create the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
with the following content:
mock-maker-inline
EDIT 2: Since Mockito 3.4.0 its now possible to mock static method too:
try (MockedStatic mocked = mockStatic(Base64.class)) {
mocked.when(() -> Base64.encodeToString(eq(array), eq(Base64.DEFAULT))).thenReturn("bar");
assertEquals("bar", Base64.encodeToString(array, Base64.DEFAULT));
mocked.verify(() -> Base64.encodeToString(any(), anyIn());
}
Furthermore you can directly add as a dependency org.mockito:mockito-inline:+
and avoid manually create the or.mockito.plugins.MockMaker file
Since Mockito 3.5.0 you can also mock object construction.