How to mock static methods
Here’s how to mock static methods step-by-step using Mockito (version 3.4 or higher, or 4.x/5.x) and JUnit 5.
✅ Requirements
- Mockito version ≥ 3.4.0
- JUnit 5
- Add the following dependencies:
<!-- For Maven -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
Or for Gradle:
testImplementation 'org.mockito:mockito-core:5.10.0'
testImplementation 'org.mockito:mockito-inline:5.10.0'
🧪 Example: Mocking a Static Method
Suppose you have a static utility class:
public class Utils {
public static String getEnv() {
return System.getenv("APP_ENV");
}
}
And a class using it:
public class AppService {
public String getEnvironmentMessage() {
String env = Utils.getEnv();
return "Environment: " + env;
}
}
✅ Mock Static Method in Test
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
public class AppServiceTest {
@Test
void testGetEnvironmentMessageWithMockedStatic() {
try (MockedStatic<Utils> mockedStatic = mockStatic(Utils.class)) {
mockedStatic.when(Utils::getEnv).thenReturn("PRODUCTION");
AppService service = new AppService();
String result = service.getEnvironmentMessage();
assertEquals("Environment: PRODUCTION", result);
}
}
}
✅ Key Points
- Use
try (MockedStatic<YourClass> ...)
for proper resource cleanup - Static mocking is temporary and thread-safe inside the block
⚠️ Limitations
- Works only with Mockito-inline
- Avoid overusing static mocking—it often signals a need for better design (e.g., dependency injection)
🔥 Bonus: Mocking Static Methods in Legacy Code
If you're dealing with very old Java code or using Java versions < 8, consider PowerMock. But for modern Java and Mockito, prefer the inline method as above.
📦 Summary
Tool/Library | Supports Static Mocking? | Notes |
---|---|---|
Mockito 3.4+ | ✅ Yes | Cleanest approach |
PowerMock | ✅ Yes | For legacy codebases only |
EasyMock, JMock | ❌ No | Don’t support static mocking |