I'm trying to mock a record class
@Test
public void testRecord() {
record Rec(){}
Mockito.mock(Rec.class);
}
But it gives the error
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class Rec
Mockito cannot mock/spy because :
- final class
at ...
Which makes sense of course.
Since version 5.x, mockito switched its default mock runner to mockito-inline.
Mockito 5 switches the default mockmaker to mockito-inline, and now requires Java 11 (see Mockito GitHub homepage)
Use mockito 5.x, if you cannot, follow previous answer below:
As the error message suggests, you cannot mock final classes with the default Mockito.
But the community came up with mockito-inline, an extension bringing experimental features such as mocking final classes and methods or static methods.
Just add this in your pom.xml and use Mockito normally.
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<scope>test</scope>
</dependency>
and for Gradle:
testImplementation 'org.mockito:mockito-inline:4.11.0'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With