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 |
Utility.calculate() using Mockito 3.4+ in a JUnit test?try (MockedStatic<Math> mathMock = Mockito.mockStatic(Math.class)) {
mathMock.when(() -> Math.max(5, 10)).thenReturn(100);
System.out.println(Math.max(5, 10));
}
System.out.println(Math.max(5, 10));@Test
void testStaticMock() {
MockedStatic<Config> configMock = Mockito.mockStatic(Config.class);
configMock.when(() -> Config.getValue()).thenReturn("mocked");
assertEquals("mocked", Config.getValue());
}Logger.log(), a static method, but you want to verify it was called exactly twice during the test. Which Mockito 3.4+ approach correctly achieves this?Pass the test and this pattern moves unknown