What is new in Mockito 5
Last week Mockito released its newest version. It is currently at version 5. With this update, we get a new mockmaker that could lead to failing tests during the upgrade. In this article, we will look into how to solve those issues.
Switch to the new Mockito-inline mockmaker
The most significant change included in version 5 is the switch of the default mockmaker. In previous versions, the default was the subclass mockmaker, which creates a subclass for each mock. Now with version 5, the default is mockito-inline. This mockmaker is based on the “inline bytecode” principle. The benefit is that it allows you to mock final classes, static methods, enums, etc., with no extra effort.
Only supports Java version 11 and higher
Mockito only supports Java version 11 and higher. If you are still running Java 8 or any of the versions between 8 and 11 you can still keep using Mockito 4.
Using the old subclass mockmaker
If some of your mocks fail because of the mockito-inline mockmaker, you can still use the subclass mockmaker for those mocked classes.
In the following example, we create a mock using the
@Mock annotation and the static
This is the class we want to create a mock instance of:
In the following example, you can see on line 13 that we create a mock using the subclass mockmaker. This was the default mockmaker in Mockito 4. On line 17, we create a mock using the new default mockito-inline mockmaker.
On line 21, we create a mock using the static
mock() method and pass it to the mockmaker we want to use as a parameter.
We looked at the biggest changes Mockito 5 brings us. The default mockmaker now is
mockito-inline. We also looked at how we
could use a different mockmaker for the test cases that need those.
Please read these release notes to see all the other changes of Mockito 5.