Skip to content
javahacks.dev
Testing

Fix Mockito Cannot Mock Final Class or Method Errors

Fix Mockito errors about final classes, records and static methods by using the inline mock maker, and decide when a final class should be an interface.

7 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the JUnit5, OpenJDK, Apache Maven and Spring logos.

Older versions of Mockito print this when you mock a final class:

Text
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class dev.javahacks.PricingClient
Mockito cannot mock/spy because :
 - final class

Mockito's default strategy was to create a subclass at runtime, and a final class or method cannot be subclassed or overridden. The inline mock maker solves it by rewriting the class's bytecode instead. Mockito 5.0 switched to it by default, so a project on Mockito 5 or newer does not hit this error for ordinary final classes. The testing background is in what to mock and what to leave real.

Check your Mockito version first

Shell
./mvnw dependency:tree -Dincludes=org.mockito

Spring Boot manages the Mockito version, so the answer is tied to your Spring Boot release. Upgrading is the cleanest fix when you are below 5.

On Mockito 4 and earlier: enable the inline maker

Add the dependency:

pom.xmlXML
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <scope>test</scope>
</dependency>

or create src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker containing a single line:

Text
mock-maker-inline

Both make mock(FinalClass.class) work. Remove them after you move to Mockito 5, where the artifact is empty and the resource is redundant.

Records, enums and static methods

The inline maker also lets you mock records and enums, which are implicitly final. It is usually a smell: a record is a value, and you should construct a real one. For static methods:

java
@Test
void usesFixedId() {
    try (MockedStatic<IdGenerator> ids = Mockito.mockStatic(IdGenerator.class)) {
        ids.when(IdGenerator::next).thenReturn("id-1");

        assertEquals("id-1", new OrderFactory().create().id());
    }
}

The mock is active only inside the try block, which is how Mockito avoids leaking static state between tests. Calls to the static from other threads are not intercepted. Static mocking works, and a static call hidden inside code is still a dependency you cannot see; pass an IdGenerator instance in and you do not need it.

The agent warning on newer JDKs

On Java 21 and later you may see:

Text
Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build.

The JDK is tightening dynamic agent loading. Pass the agent explicitly, for example in Maven Surefire:

XML
<argLine>-javaagent:${settings.localRepository}/org/mockito/mockito-core/${mockito.version}/mockito-core-${mockito.version}.jar</argLine>

The Mockito documentation on the inline mock maker describes the options.

Should it be mockable at all?

If you own the final class, ask whether a test double should replace it. Often the better design is a small interface that your code depends on, with the final class as one implementation and a hand-written fake in tests:

java
interface Pricing { long priceFor(String sku); }

class FakePricing implements Pricing {
    public long priceFor(String sku) { return 100; }
}

A fake has real behavior and cannot drift into a mock whose stubs no longer match the class. The vocabulary is in test doubles explained.

What Mockito 5 can mock, and what it still refuses

The usual advice, "add the inline mock maker", describes Mockito 4 and earlier. From Mockito 5 the inline mock maker is the default, so final classes, final methods, records and static methods can all be mocked with no configuration. This test class exercises each case on Mockito 5.20.0 and JUnit 6.0.0.

FinalTest.javajava
class FinalTest {
    static final class Clock3 { String now() { return "real"; } static String id() { return "real-static"; } }
    record Money(long cents) { long doubled() { return cents * 2; } }

    @Test void mocksFinalClass() {
        Clock3 mock = mock(Clock3.class);
        when(mock.now()).thenReturn("fake");
        assertEquals("fake", mock.now());
    }

    @Test void mocksRecord() {
        Money m = mock(Money.class);
        when(m.doubled()).thenReturn(99L);
        assertEquals(99L, m.doubled());
    }

    @Test void staticNeedsMockStatic() {
        try (var s = mockStatic(Clock3.class)) {
            s.when(Clock3::id).thenReturn("fake-static");
            assertEquals("fake-static", Clock3.id());
        }
        assertEquals("real-static", Clock3.id());
    }

    @Test void extraInterfacesOnFinal() {
        mock(Clock3.class, withSettings().extraInterfaces(Runnable.class));
    }
}
Text
mocksFinalClass()          ✔
mocksRecord()              ✔
staticNeedsMockStatic()    ✔
extraInterfacesOnFinal()   ✘
   Mockito cannot mock this class: class FinalTest$Clock3.
   Can not mock final classes with the following settings :
    - explicit serialization (e.g. withSettings().serializable())
    - extra interfaces (e.g. withSettings().extraInterfaces(...))

Three of four pass untouched. The failing case is the message this post is about, and it shows the exact limit: a final class cannot be mocked when the mock must implement extra interfaces or be serializable, because the inline mock maker redefines the existing class and cannot add to its type hierarchy. If you see this message on Mockito 5, look for extraInterfaces or serializable() in the mock settings, often hidden in a shared test utility, rather than hunting for a missing configuration file.

The static block deserves a note. mockStatic returns a scoped mock that is active on the current thread only until the try block ends, and the last assertion proves the real method returns after it. Forgetting the try-with-resources leaves the static mock registered and breaks the next test on that thread, which is why the API insists on AutoCloseable.

If you are on Mockito 4 or earlier

Older versions use a subclass-based mock maker, and a final class fails with a similar message: Cannot mock/spy class X ... Mockito cannot mock/spy because: final class. Switch the mock maker to inline in one of two ways. Replace the dependency with mockito-inline, or add a file to the test resources.

Text
src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
Text
mock-maker-inline

The file has one line and no extension. Upgrading to Mockito 5 removes the need entirely, and Spring Boot 4 manages a Mockito 5 version, so this is mostly relevant for projects stuck on an old Boot line.

Prefer a seam to a final-class mock

That you can mock a final class does not mean you should. Mocking java.time.Clock or a vendor SDK client couples the test to the exact calls the production code makes, and the test breaks when you refactor without changing behaviour. Wrap the dependency in a small interface that you own and mock or fake that.

java
interface Now { Instant get(); }

class SystemNow implements Now { public Instant get() { return Instant.now(); } }

// in the test, no mocking framework at all
Now fixed = () -> Instant.parse("2025-03-14T09:00:00Z");

The lambda replaces the final class and the mocking library at once. Keep the mock for the boundary you cannot wrap, for instance a final class in a third-party client that you call in one place, and keep that place thin.

Check what mocking a final method actually changed

An inline mock replaces behaviour in the JVM's loaded classes, which has a price. Mocking final classes can slow the first use by a small amount and requires an agent: Mockito 5 attaches byte-buddy-agent at run time, and on JDK 21 and later the JVM prints a warning that a dynamic agent was loaded unless you pass -XX:+EnableDynamicAgentLoading or add Mockito as an explicit -javaagent. Surefire can do that for you.

XML
<plugin>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
    <argLine>-javaagent:${settings.localRepository}/org/mockito/mockito-core/${mockito.version}/mockito-core-${mockito.version}.jar</argLine>
  </configuration>
</plugin>

The explicit agent is the setting recommended by the Mockito project for JDK 21 and later, and it removes the warning and a future compatibility risk.

Mock at the boundary you own

A pattern avoids most final-class mocking: wrap the third-party class in a small adapter you own, mock the adapter in tests, and test the adapter once against the real class. The adapter's methods are named for what your application needs, not for what the library offers, so the tests read in the language of your domain and a change of library touches one class.

java
interface PaymentGateway { Receipt charge(Money amount, CardToken token); }

class StripeGateway implements PaymentGateway {
    private final com.stripe.StripeClient client;       // final classes, hard to mock
    public Receipt charge(Money amount, CardToken token) { /* map to the vendor API */ }
}

Tests for the service that uses PaymentGateway use a lambda or a Mockito mock of the interface, with no inline mock maker involved. A single integration test with the vendor's test mode covers StripeGateway. The result is fewer tests that depend on the exact vendor calls and a code base that survives a vendor upgrade with changes in one place.

Where this does not apply

If the error mentions a class from the JDK, such as String or Thread, those are intentionally not mockable; wrap them. If Mockito fails with MockitoException: Mockito cannot mock this class for a class that is not final, it may be a primitive wrapper, a sealed type or a class from a locked module. For how the choice fits a whole suite, see the test pyramid. The Mockito wiki on mocking final types and the Java agent documentation cover the details.

Also inJUnit
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.