Mocking static methods (Mockito 3.4+) in JUnit - Build an Automation Script
import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; class Calculator { public static int add(int a, int b) { return a + b; } } class MathService { public int calculateSum(int x, int y) { return Calculator.add(x, y); } } public class MathServiceTest { @Test void testCalculateSumWithMockedStatic() { try (MockedStatic<Calculator> mockedStatic = mockStatic(Calculator.class)) { // Arrange: mock static method to always return 10 mockedStatic.when(() -> Calculator.add(anyInt(), anyInt())).thenReturn(10); MathService service = new MathService(); // Act int result = service.calculateSum(3, 7); // Assert assertEquals(10, result, "The mocked static method should return 10"); // Verify static method was called once with arguments 3 and 7 mockedStatic.verify(() -> Calculator.add(3, 7), times(1)); } } }
This test mocks the static method Calculator.add using Mockito's mockStatic feature introduced in version 3.4+. The try-with-resources block ensures the static mock is closed after the test to avoid side effects.
Inside the block, we set the static method to always return 10 regardless of input. Then we call MathService.calculateSum(3, 7), which internally calls the mocked static method.
We assert the returned value is 10, confirming the mock worked. Finally, we verify that the static method was called exactly once with the expected arguments (3 and 7). This ensures the method interaction is correct.
This approach keeps the test isolated, clean, and uses best practices for mocking static methods with Mockito 3.4+ and JUnit 5.
Now add data-driven testing with 3 different input pairs for calculateSum and verify the mocked static method returns 10 each time