Java
Mockito
Unit Testing
Static Methods
Software Development

Mocking static methods with Mockito

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Mockito is a popular mocking framework for unit tests in Java. Traditionally, mocking static methods has been complicated because Mockito did not support it directly. However, starting from Mockito 3.4.0, the addition of the mockito-inline artifact allows for mocking of static methods, opening new possibilities for unit testing code that uses static calls.

Understanding the Challenge with Static Methods

Static methods belong to the class rather than any instance of the class. This nature makes them have a global state which, in turn, makes testing environments prone to side effects if not handled appropriately. Prior to Mockito 3.4.0, developers relied on other tools like PowerMock, which extends Mockito capabilities to deal with such scenarios. The ability to mock static methods directly with Mockito simplifies test setups and reduces the leaning curve for new developers.

Setting Up Mockito for Static Method Mocking

To begin mocking static methods with Mockito, you will need to ensure you include the mockito-inline dependency in your project. Here is an example of how you might set up this dependency using Maven:

xml
1<dependency>
2    <groupId>org.mockito</groupId>
3    <artifactId>mockito-inline</artifactId>
4    <version>3.4.0</version>
5    <scope>test</scope>
6</dependency>

How to Mock Static Methods

To mock a static method with Mockito, you use the MockedStatic interface provided by Mockito. This interface functions similarly to the standard mocking mechanism but specifically targets static methods. Here’s how you do it:

  1. Start a mock session: Use Mockito.mockStatic(ClassToMock.class) to start a static mock session. This returns a MockedStatic instance which will be used to configure and verify the static calls.
  2. Specify the behavior: Once the session is started, you can define the behavior of the static methods using typical Mockito syntax (when(), thenReturn(), etc.).
  3. Close the mock session: The mock session should be closed after each test to ensure there's no state carry-over between tests. This is typically handled within a try-with-resources block to ensure automatic closure.

Example

Suppose you have a utility class with a static method:

java
1public class Utility {
2    public static String status() {
3        return "Up and running";
4    }
5}
6

You can test a class that uses this static method using Mockito as shown below:

java
1import org.mockito.MockedStatic;
2import org.mockito.Mockito;
3
4import static org.junit.jupiter.api.Assertions.assertEquals;
5import static org.mockito.Mockito.*;
6
7public class SystemCheckerTest {
8    @Test
9    public void testSystemStatus() {
10        try (MockedStatic<Utility> utilities = Mockito.mockStatic(Utility.class)) {
11            utilities.when(Utility::status).thenReturn("System Overload");
12            
13            String actualStatus = Utility.status();
14            assertEquals("System Overload", actualStatus);
15        }
16    }
17}

Key Considerations

While Mockito now supports static method mocking, it should be used judiciously. Static method mocking can signify poor design choices leading to tightly coupled and less maintainable code. Therefore, consider design patterns and principles (like Dependency Injection) that may help in writing more testable and modular code.

Summary Table

FeatureToolUsage ScopeLimitations
Static Method MockingMockito prior v3.4.0Not supported directlyRequired third-party extensions
Static Method MockingMockito v3.4.0+Supported with mockito-inlineContinued caution for design impact

In conclusion, Mockito's ability to mock static methods can significantly simplify testing in Java where static methods are used. The practical application of this feature should, however, be managed with consideration for good coding practices and design principles.


Course illustration
Course illustration

All Rights Reserved.