DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Edited on

Mock static methods with Mockito - Java Unit Testing

One of the most frustrating element when I am doing the Unit tests in Java is to not be able to mock static methods.

Sure, during a long time we got PowerMock. But, since JUnit5, PowerMock wasn't compatible and we were unable to continue with it.


But now, we have this feature included in Mockito!

Dependencies

First, you have to add the mockito-inline library. (You can use any version up to 3.4.0)

Here is an exemple with Maven

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <version>3.9.0</version>
    <scope>test</scope>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Writing test

To mock a static method, you have to create a mockStatic of the class with the static method, and declare the event you want to apply to your mock.

example

@Test
public void test() {

try (MockedStatic<LoggerFactory> loggerFactoryMock = Mockito.mockStatic(LoggerFactory.class)) {
            loggerFactoryMock.when(() -> LoggerFactory.getLogger(any(Class.class))).thenReturn(loggerMock);

...
            verify(loggerMock, times(1)).error("Err message test");
...
        }
    }
Enter fullscreen mode Exit fullscreen mode

Then, you just have to run your tests!


I hope it will help you!

Top comments (0)