DEV Community

loading...

Mock static methods with Mockito - Java Unit Testing

Maxime Guilbert
Just a dev who touches a lot of things and wants to share his experiences. (or just want to note somewhere things to don't forget)
・1 min read

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!

Discussion (0)

Forem Open with the Forem app