Introduction
This post explains how to mock static methods. Mockito doesn't support this behavior by default. To stub static methods, we need to enable the inline mock maker first.
Maven Dependency
For the examples, I used version 4.2.0
of Mockito.
|
|
We also need the inline mock maker to stub static methods. We can add a dependency or create a file inside the test resources to enable the new Mock maker.
Option 1: Inline mock maker dependency
Add this dependency in your pom.
|
|
Option 2: Adding a file to enable the inline mock maker
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.
Mocking 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.
|
|
Conclusion
In this post, we enabled the inline mock maker to mock static methods. We 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 https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html. It lists all the Mockito features and how to use them.
Further reading
More about testing in Java: