This article will be covering mocking static methods with Mockito. We will try to answer the question is this even possible to do it and why should we ever mock anything that is static.
2. Static methods
Let's start with a simple definition. Static methods are that methods in Java that can be called without creating an instance of the class. A static method belongs to the class rather than the object of a class.
Using static methods in Java is sometimes necessary, however, most developers limit their use to pure functions which are independent (not using external dependencies). Whether we like them or not, we do sometimes have to rely on them and also mock them in unit tests.
3. Mocking static method with Mockito 3.x
The good news is that from the latest Mockito version mocking static methods is finally supported.
To make this possible, a single dependency had to be added to the pom.xml file:
The PowerMock uses internally Mockito API so we still need the Mockito library in our dependencies.
The following shows how to create a test that mocks the static WelcomeUtil.generateWelcome(...) method just like in the above example:
In this example mockStatic(...) and when(...) methods comes from PowerMockito library.
5. Mocking static method with Mockito 4.x
What about Mockito in version 4.x? The same as for 3.x, you will still need the mockito-inline library to mock static methods otherwise the system will throw a MockitoException. The good news is that we don't have to declare mockito-core separately because mockito-inline uses mockito-core as dependency.
6. Conclusion
In this article, we presented how to mock static methods with Mockito and PowerMockito libraries. When it is not about mocking methods from third-party libraries, consider refactoring the code so that mocking a static method wouldn't be necessary. It is always not the best solution.
Test examples used in this article, are available in the GitHub Repository:
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}