Skip to content
Latchkey

Mockito "Cannot mock/spy final class" in CI - Enable the Inline Mock Maker

By default the legacy Mockito mock maker uses subclassing, which cannot mock final classes/methods (including most Kotlin classes). The fix is the inline mock maker - default in Mockito 5, opt-in in Mockito 2-4.

What this error means

A test fails with org.mockito.exceptions.base.MockitoException: Cannot mock/spy class ... because : final class (or final method). Common with Kotlin, records, and library final types.

junit
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class com.example.PriceService
Mockito cannot mock/spy because :
 - final class

Common causes

Subclass mock maker on a final type

The default mock maker creates a subclass, which is impossible for final classes/methods, so Mockito refuses.

Inline mock maker not enabled (Mockito < 5)

On Mockito 2-4 you must opt into mock-maker-inline; without it final types cannot be mocked.

How to fix it

Use mockito-core 5+ (inline by default)

The simplest fix is to upgrade; Mockito 5 ships the inline mock maker by default.

pom.xml
<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-core</artifactId>
  <version>5.12.0</version>
  <scope>test</scope>
</dependency>

Or enable the inline mock maker on Mockito 2-4

Add the resource file that selects the inline maker.

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

How to prevent it

  • Standardize on Mockito 5+ for inline mocking, or commit the MockMaker resource, so final classes and Kotlin types mock without per-test workarounds.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →