Contents

Upgrading to Mockito 5

Writen by: David Vlijmincx

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 mock() method.

This is the class we want to create a mock instance of:

1
2
3
public class Person{
    // Your code...
}

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockMakers;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.mockito.Mockito.withSettings;

@ExtendWith(MockitoExtension.class)
public class TestingDifferentMockMakers {

    @Mock(mockMaker = MockMakers.SUBCLASS)
    Person subclassMockPerson;
    
    @Mock(mockMaker = MockMakers.INLINE)
    Person inlineMockPerson;
    
    @Test
    void testingMethod(){
        Person mock = Mockito.mock(Person.class, withSettings().mockMaker(MockMakers.SUBCLASS));
    }
}

Conclusion

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.