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 programs 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 without 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.
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: