Explain Codes LogoExplain Codes Logo

How to mock a final class with Mockito

java
mockito
testing
best-practices
Nikita BarsukovbyNikita Barsukov·Oct 27, 2024
TLDR

Mockito 2+ empowers you to mock final classes. Add mockito-inline to your Gradle or Maven dependencies to unleash this power:

// For Gradle: testImplementation 'org.mockito:mockito-inline:2.26.0' // For Maven: <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-inline</artifactId> <version>2.26.0</version> <scope>test</scope> </dependency>

Now we can mock with style:

import static org.mockito.Mockito.*; // Mocking this final class is our destiny! FinalClass mockFinal = mock(FinalClass.class); /* Think of this like getting back your favorite toy from when you were a kid, it's your rules now! */ when(mockFinal.someMethod()).thenReturn("Mocked Toy");

To power-up your tests, create a file named org.mockito.plugins.MockMaker in src/test/resources/mockito-extensions with the nuclear codes mock-maker-inline.

While legacy code or third-party libraries might seem like impassable roads because of final classes, Mockito provides us with a road roller to flatten the bumps and test in peace.

Mocking best practices

Reassess your design

Use the final keyword with intentionality. If it's your code, open up interfaces or abstract classes for more oxygen in your test environment.

Camel, not a giraffe!

Catch the camel, drop the giraffe! Inline mocking is powerful but nailing every nail with a sledgehammer is overkill. Use it judiciously for a happy Mockito Safari!

Byte Buddy saves the day

Byte Buddy is the Sherlock to your mocking miseries. Although it usually solves cases silently, you might need some configuration for complex settings.

Alternate routes to mocking

Use a delegate

Having difficulties? Wrap the final class in a non-final delegate and have the delegate take the mock shots. More code, but less headache!

Fake it till you make it

When appropriate, fake objects might be your ticket out of the mocking maze. Often simpler, and the ticket is cheaper!

Issues in Warrior's Path

Plugin file playing hide-and-seek

If Mockito doesn't recognize your org.mockito.plugins.MockMaker file, check if it's attempting a hide-and-seek. Make sure it's playing by the rules of the game.

A dependency clash of clans

Ensure there's no kingdom battle between versions of your dependencies. A peaceful kingdom is a productive kingdom!

Byte Buddy being a double agent

If Mockito seems to be playing dumb and not initializing properly, investigate if Byte Buddy is the double agent causing the mess. A little cleanup might be needed.