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.

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 mock object that you can use to set up the test behavior for the static method.

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 java.util.List;

import org.junit.Test;

public class StaticMethodMockingExample {
  @Test
  public void testStaticMethod() {
    // Create a mock of the List class
    mockStatic(List.class);

    // Set up the test behavior for the static method
    when(List.size()).thenReturn(100);

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

In this example, the size() method of the java.util.List class is a static method that returns the size of the list. The mockStatic() method creates a mock object for the List class, and the when() method is used to set up the test behavior for the size() method, which returns the value 100.

The testStaticMethod() test method then calls the size() method and checks that the returned value is 100.

Note that when you use mockStatic() to mock a static method, the mock behavior is applied to all instances of the class. To reset the mock behavior and restore the original behavior of the static method, you can use the reset() method of the org.mockito.Mockito class.

For example, to reset the mock behavior of the List class after the testStaticMethod() test is finished, you can do the following:

import static org.mockito.Mockito.reset;

import org.junit.After;

public class StaticMethodMockingExample {
  @After
  public void resetMock() {
    reset(List.class);
  }
  ...
}

This will reset the mock behavior of the List class, so that the original behavior of the static methods is restored.