Introduction
This article looks at how to mock a Record in Java. Mockito 5 made this very easy. Using Mockito 5 you can mock a Record as you would mock any other class. If you are using Mockito 4, you need to enable the mock-maker-inline to mock Records.
Setup using Mockito 5
Mockito 5 has the mock-maker-inline enabled by default. When using Mockito version 5 or higher, you don't have to add a new dependency or add a text file to the test resources. Mocking records will work out of the box.
The maven dependency for mockito 5:
|
|
Setup using Mockito 4
If you are already using mockito 4 and can't upgrade, you need to enable the mock-maker-inline first. There are two ways to do so: by adding a dependency or by creating a file.
Option 1: Mock maker inline dependency
Add this dependency in your pom.xml to enable Mockito's Mock maker inline. We need the Mock maker inline to mock constructors.
|
|
Option 2: Adding a file to enable the Mock maker inline
If you don't want to or can't add a dependency, you can also use a file to enable the mock maker inline.
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.
Testing code
The following piece of code is the Record we are going to mock inside the testing class.
|
|
With the mock maker inline enabled, which is the default in Mockito 5. We can mock the record class in the test method. In the following example, we have a test method that creates two mocks of the Record Person.
|
|
Conclusion
In this post, we enabled the inline mock maker to mock constructors. We saw that with Mockito version 5, we no longer need to enable the mock-maker-inline ourselves because it is enabled by default. With Mockito 4, we need to enable the mock-maker-inline before we can write our tests. In the last example, we saw how to mock a Record in Java with Mockito.
Further reading
More about testing in Java: