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.
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class com.example.PriceService
Mockito cannot mock/spy because :
- final classCommon 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.
<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.
// src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
mock-maker-inlineHow to prevent it
- Standardize on Mockito 5+ for inline mocking, or commit the
MockMakerresource, so final classes and Kotlin types mock without per-test workarounds.