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.
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.
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); } } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initialized | - | PASS |
| 2 | Mocks static method Utility.getGreeting using mockStatic | Static method getGreeting is mocked to return 'Mocked Hello!' | - | PASS |
| 3 | Calls Utility.getGreeting() | Static method call intercepted by mock | Check that returned value is 'Mocked Hello!' | PASS |
| 4 | Assert that result equals 'Mocked Hello!' | Assertion compares expected and actual values | assertEquals("Mocked Hello!", result) | PASS |
| 5 | Test ends and mock is closed | Static mocking context closed, original method restored | - | PASS |