0
0
JUnittesting~10 mins

Mocking static methods (Mockito 3.4+) in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test verifies that a static method can be mocked using Mockito 3.4+ in a JUnit test. It checks that the mocked static method returns the expected value when called.

Test Code - JUnit with Mockito 3.4+
JUnit
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;

class Utility {
    public static String getGreeting() {
        return "Hello, World!";
    }
}

public class StaticMockTest {
    @Test
    void testMockStaticMethod() {
        try (MockedStatic<Utility> mockedStatic = mockStatic(Utility.class)) {
            mockedStatic.when(Utility::getGreeting).thenReturn("Mocked Hello!");

            String result = Utility.getGreeting();

            assertEquals("Mocked Hello!", result);
        }
    }
}
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2Mocks static method Utility.getGreeting using mockStaticStatic method getGreeting is mocked to return 'Mocked Hello!'-PASS
3Calls Utility.getGreeting()Static method call intercepted by mockCheck that returned value is 'Mocked Hello!'PASS
4Assert that result equals 'Mocked Hello!'Assertion compares expected and actual valuesassertEquals("Mocked Hello!", result)PASS
5Test ends and mock is closedStatic mocking context closed, original method restored-PASS
Failure Scenario
Failing Condition: Static method is not mocked correctly or mockStatic is not used
Execution Trace Quiz - 3 Questions
Test your understanding
What does mockStatic(Utility.class) do in this test?
AIt disables the Utility class
BIt creates a mock instance of Utility class
CIt creates a mock for all static methods of Utility class
DIt calls the real static method
Key Result
Always use try-with-resources when mocking static methods with Mockito to ensure the mock is active only during the test and original behavior is restored after.