0
0
JUnittesting~15 mins

Mocking static methods (Mockito 3.4+) in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify behavior of a method that calls a static utility method
Preconditions (2)
Step 1: Mock the static method Calculator.add to return a fixed value 10 regardless of input
Step 2: Call MathService.calculateSum with inputs 3 and 7
Step 3: Verify that the returned value from calculateSum is 10
Step 4: Verify that the static method Calculator.add was called exactly once with arguments 3 and 7
✅ Expected Result: The test passes confirming that the static method was mocked correctly and MathService.calculateSum returns the mocked value
Automation Requirements - JUnit 5 with Mockito 3.4+
Assertions Needed:
Assert that MathService.calculateSum returns the mocked value 10
Verify that Calculator.add static method was called once with correct arguments
Best Practices:
Use try-with-resources to open and close the static mock context
Use Mockito's mockStatic method to mock static methods
Use explicit verification of static method calls
Keep test isolated and independent
Automated Solution
JUnit
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.

Common Mistakes - 4 Pitfalls
Not using try-with-resources to close the static mock
Using Mockito.mock() instead of Mockito.mockStatic() for static methods
{'mistake': 'Not verifying the static method call with correct arguments', 'why_bad': "Without verification, you don't confirm that the static method was called as expected, reducing test reliability.", 'correct_approach': 'Use mockedStatic.verify() with exact arguments to ensure correct method invocation.'}
Mocking static methods globally without scoping
Bonus Challenge

Now add data-driven testing with 3 different input pairs for calculateSum and verify the mocked static method returns 10 each time

Show Hint