W3docs

Mocking static methods with Mockito

Mockito is a popular mocking framework for Java. It allows you to create mock objects and set up test behavior for them.

Mockito is a popular mocking framework for Java. It allows you to create mock objects and set up test behavior for them.

To mock a static method with Mockito, you can use the mockStatic() method of the org.mockito.Mockito class. This method takes the class containing the static method as an argument and returns a MockedStatic object. You should use a try-with-resources statement to ensure the mock is properly closed after the test.

Here is an example of how you can use mockStatic() to mock a static method with Mockito:


import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.mockito.MockedStatic;

class MyUtils {
    public static int getStaticValue() {
        return 0;
    }
}

public class StaticMethodMockingExample {
    @Test
    public void testStaticMethod() {
        try (MockedStatic<MyUtils> mockedUtils = mockStatic(MyUtils.class)) {
            // Set up the test behavior for the static method
            mockedUtils.when(MyUtils::getStaticValue).thenReturn(100);

            // Test the code that calls the static method
            int result = MyUtils.getStaticValue();
            assertEquals(100, result);
        }
    }
}

In this example, getStaticValue() is a static method in the MyUtils class. The mockStatic() method creates a mock context for the class, and when() is used to define the return value. The try-with-resources block ensures the mock is automatically closed after the test completes.

Note that static mocking affects the class itself, not individual instances. To reset the mock behavior and restore the original implementation, you can call the close() method on the MockedStatic instance, or simply use a try-with-resources block to handle it automatically.