From Mockito 3.4.0, it is possible to mock static method even in Junit 5 thus reducing the dependency on using PowerMock.
To use this, add dependency with mockito-inline >= 3.4.0
and remove dependency on mockito-core
if it exists.
Let’s consider the usecase where we need to write unit Test for the Lambda class created in this blog where we used Guice.createInjector
for dependency injection.
- Mock Injector
@Mock
private Injector injector;
- Create a
@BeforeEach
method which mocks theGuice
class and initializes the Lambda class
@BeforeEach
public void setup() {
try(MockedStatic<Guice> guiceMockedStatic = mockStatic(Guice.class)) {
guiceMockedStatic.when(() -> Guice.createInjector(any(ApplicationModule.class))).thenReturn(injector);
Mockito.doReturn(bookService).when(injector).getInstance(Mockito.eq(UserService.class));
testLambda = new TestLambda(); // or perform any assert operation if testing the static method directly
}
}
The above example provides mocking a static method with arguments.
To mock a static method without arguments
try(MockedStatic<TestStatic> mockedstatic = mockStatic(TestStatic.class)) {
mockedstatic.when(TestStatic::getTestData).thenReturn("TestData");
assetEquals("TestData", TestStatic.getTestData());
}
Note that if you want to test a static method you have created, it is worth investigating if it can be refactored and make it more testable as it hints a code smell.
We need to mock static methods sometimes especially when we are working with the methods in dependent library eg. Guice in this post.