This post explains how to mock final methods and classes. Mockito doesn't support this behavior by default. To stub final methods and mock final classes, we need to enable the inline mock maker first.
For the examples, I used version
4.2.0 of Mockito.
We also need the inline mock maker to stub final classes/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
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:
In the file
org.mockito.plugins.MockMaker paste this text
mock-maker-inline, now the mock maker is available during tests.
Mocking final class and methods
With inline mock maker, mocking a final class or method is the same as mocking a non-final class or method. Below we have an
example that mocks the final class
Cat. You can't tell from the @Test annotated method that we mock a final class.
Mocking final methods also doesn't look any different from mocking a non-final method.
In this post, we enabled the inline mock maker to mock final methods and classes. We also saw two examples of how to mock a final class and method and that it looks the same as mocking non-final classes and methods.
If you're 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.
More about testing in Java: