Sometimes, you need to test code that calls static methods. Mocking static methods lets you replace their behavior during tests to control results and avoid side effects.
Mocking static methods (Mockito 3.4+) in JUnit
try (MockedStatic<ClassName> mockedStatic = Mockito.mockStatic(ClassName.class)) { mockedStatic.when(() -> ClassName.staticMethod(args)).thenReturn(mockedValue); // test code that calls ClassName.staticMethod }
Use try-with-resources to automatically close the static mock after the test.
Inside the try block, you define what the static method should return or do.
try (MockedStatic<Math> mathMock = Mockito.mockStatic(Math.class)) { mathMock.when(() -> Math.max(1, 2)).thenReturn(10); int result = Math.max(1, 2); assertEquals(10, result); }
try (MockedStatic<Utils> utilsMock = Mockito.mockStatic(Utils.class)) { utilsMock.when(() -> Utils.getConfig()).thenReturn("mockedConfig"); String config = Utils.getConfig(); assertEquals("mockedConfig", config); }
This test mocks the static method Calculator.add(2, 3) to return 100 instead of 5. The assertion checks that the mocked value is returned.
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; class StaticMethodTest { static class Calculator { static int add(int a, int b) { return a + b; } } @Test void testMockStaticAdd() { try (MockedStatic<Calculator> mocked = Mockito.mockStatic(Calculator.class)) { mocked.when(() -> Calculator.add(2, 3)).thenReturn(100); int result = Calculator.add(2, 3); assertEquals(100, result); } } }
Mockito static mocking requires Mockito 3.4 or higher and JUnit 5 for best integration.
Always use try-with-resources to avoid static mocks leaking between tests.
Mocking static methods can make tests harder to read; use it only when necessary.
Mocking static methods lets you control static method behavior during tests.
Use try-with-resources and Mockito.mockStatic to create static mocks.
This helps isolate code and test units that depend on static methods.
Practice
Solution
Step 1: Understand mocking purpose
Mocking allows us to simulate or control method behavior during tests to isolate code.Step 2: Apply to static methods
Mockito 3.4+ supports mocking static methods to control their output in tests.Final Answer:
To control and simulate the behavior of static methods during testing -> Option AQuick Check:
Mocking static methods = control behavior [OK]
- Thinking mocking improves production performance
- Confusing static with instance methods
- Assuming mocking generates test data automatically
Utility.calculate() using Mockito 3.4+ in a JUnit test?Solution
Step 1: Use try-with-resources for static mocking
Mockito.mockStatic requires try-with-resources to auto-close the mock.Step 2: Use method reference in when()
Correct syntax uses mocked.when(Utility::calculate) to mock static method.Final Answer:
try (MockedStatic<Utility> mocked = Mockito.mockStatic(Utility.class)) { mocked.when(Utility::calculate).thenReturn(10); } -> Option AQuick Check:
try-with-resources + method ref = correct syntax [OK]
- Omitting try-with-resources block
- Calling mockStatic on method instead of class
- Using wrong lambda syntax in when()
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));Solution
Step 1: Inside try block, static method is mocked
Math.max(5, 10) returns 100 because of mocked behavior.Step 2: Outside try block, mock is closed
Math.max(5, 10) returns normal value 10 after mock is closed.Final Answer:
100 10 -> Option BQuick Check:
Mock active = 100, mock closed = 10 [OK]
- Assuming mock affects calls outside try block
- Expecting mock to persist after try block
- Confusing return values of Math.max
@Test
void testStaticMock() {
MockedStatic<Config> configMock = Mockito.mockStatic(Config.class);
configMock.when(() -> Config.getValue()).thenReturn("mocked");
assertEquals("mocked", Config.getValue());
}Solution
Step 1: Check static mock resource management
Static mocks must be closed; try-with-resources ensures this automatically.Step 2: Identify missing try block
Code creates mock but does not close it, risking side effects.Final Answer:
Missing try-with-resources block to close the static mock -> Option CQuick Check:
Always use try-with-resources for static mocks [OK]
- Not closing static mocks causing test interference
- Using wrong lambda syntax in when()
- Mixing up assertEquals argument order
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?Solution
Step 1: Use try-with-resources to mock static Logger
Static mock must be created and closed properly.Step 2: Call Logger.log() twice inside try block
To verify calls, method must be invoked during mock lifetime.Step 3: Verify Logger.log() called exactly twice
Use loggerMock.verify with times(2) after calls.Final Answer:
try (MockedStatic<Logger> loggerMock = Mockito.mockStatic(Logger.class)) { Logger.log(); Logger.log(); loggerMock.verify(() -> Logger.log(), Mockito.times(2)); } -> Option DQuick Check:
Call methods inside try, then verify calls [OK]
- Verifying calls without invoking method
- Not using try-with-resources for static mocks
- Using Mockito.verifyStatic without proper context
Ready to prove it?
Pass the test and this pattern moves unknown
