Programming & Development / April 11, 2025

How to Mock Static Methods in Java with Mockito (Modern Approach)

mock static method java mockito static methods mockito mockstatic java mock static mockito inline mock static utility class junit mock static static method testing java

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.


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex