How to mock a record with Mockito

Viewed 2083

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.

1 Answers

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>
Related