Introduction
This post explains how to mock static methods. You learn to how to use mockito with static methods. Since Mockito 5 this can be done by default.
Maven Dependency
For the examples, I used version 5.4.0
of Mockito.
|
|
Mockito 5 made the mock-maker-inline the default, this removes the need to add an extra dependency or create a special file.
Using Mockito 4?
If you can't upgrade to Mockito 5, you can use these dependencies:
|
|
The first dependency is for Mockito. The second dependency is to enable the mock maker inline as default. If you don't want the second dependency, at the end of this post you will learn how to change the deafult using a file.
Mock Static Method
With MockedStatic
, we can stub static methods of a class. The code uses try-with-resources to limit the scope of the stubbing
to only within that try statement. The example below shows how to mock the static method Instant.now()
. We first create a
mock of Instant
for the static method to return. Then we stub the static method and make it return the
object we created earlier. Every time we call the stubbed static method we get our mocked object back.
|
|
Mock static method and change the default behavior
This example looks the same as the stubbing example, but now we pass an extra parameter to MockedStatic
. When we pass
withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)
to the mockStatic
method, we call the real method for the methods
we didn't stub. By default, if we don't supply the extra parameter, it will behave
like any other mockito mock and return null when we call methods we didn't stub. The example below shows how to stub a static
method and pass other calls to the real methods.
|
|
Enable inline mock maker for Mockito 4 with a file
If you don't want to add a dependency you can also create a special file telling Mockito to use the mock maker inline like this:
Create a resources
directory in your test
directory if you do not have one already. Inside the resources
create the directory mockito-extensions
and in
that directory the file org.mockito.plugins.MockMaker
. The complete path with file should look like this: src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
.
In the file org.mockito.plugins.MockMaker
paste this text mock-maker-inline
, now the mock maker is available during tests.
Conclusion
In this post, you learned how to mock a static method with Mockito. You also saw two examples of how to create a MockedStatic
object and change its default behavior.
If you are curious and want to know more about what you can do with Mockito, please check out their documentation. It lists all the Mockito features and how to use them.
Further reading
More about testing in Java: