Article:
Introduction
Mocking static methods in Java used to require workarounds or additional frameworks like PowerMock. But with the introduction of mockStatic()
in Mockito 3.4+ and Mockito 4+, mocking static methods has become simple, clean, and officially supported.
In this article, you'll learn how to mock static methods in Java using Mockito, including the required setup and best practices.
π¦ Requirements
To mock static methods using Mockito, youβll need:
- Mockito version 3.4.0+ or 4.x
mockito-inline
dependency
Maven Setup:
xml
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>5.12.0</version> <!-- Use latest -->
<scope>test</scope>
</dependency>
π§ͺ Example: Mocking a Static Utility Method
Letβs say you have a simple utility class:
java
public class Utility {
public static String getEnv() {
return System.getenv("ENV");
}
}
You want to mock Utility.getEnv()
in a test.
Here's how to do it:
java
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
public class UtilityTest {
@Test
void testGetEnvWithMockedStatic() {
try (MockedStatic<Utility> mocked = mockStatic(Utility.class)) {
// Define mocked behavior
mocked.when(Utility::getEnv).thenReturn("mocked-env");
// Use the mocked method
String result = Utility.getEnv();
// Assertions
assertEquals("mocked-env", result);
// Verify method call
mocked.verify(Utility::getEnv);
}
}
}
π‘ Explanation:
mockStatic()
opens a scoped mock for the static class.- Itβs wrapped in a
try-with-resources
block to automatically release the mock. - You can define behavior with
when(...).thenReturn(...)
just like instance mocks. - You can also verify static method calls.
π‘ Best Practices
- Use sparingly: Static method mocking is powerful but should be used when refactoring isn't possible.
- Refactor if possible: If you can convert static calls to dependency-injected services, your code becomes more testable and maintainable.
- Scope your mocks: Always use
mockStatic
in a try-with-resources block to avoid side effects.
β Common Pitfalls
- Forgetting to include
mockito-inline
β Mockito core does not support static mocking on its own. - Trying to mock outside the scoped block β mocked behavior only works inside
try(...) { }
. - Not using JDK 8+ or an up-to-date version of Mockito β older environments may not support this feature.
π Conclusion
Mocking static methods in Java is now easy and elegant with the latest versions of Mockito. Whether you're testing legacy code or utility classes, mockStatic()
gives you full control in unit tests without relying on clunky third-party tools.
By following best practices and keeping your mocks scoped and focused, you can maintain clean, testable codebases β even when static methods are involved.