Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a record with Mockito

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.

like image 883
apflieger Avatar asked Dec 14 '25 06:12

apflieger


1 Answers

Update 15/Nov/2023

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'
like image 188
thchp Avatar answered Dec 15 '25 20:12

thchp