How to mock a final class with Mockito
Mockito 2+ empowers you to mock final
classes. Add mockito-inline
to your Gradle or Maven dependencies to unleash this power:
Now we can mock with style:
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
.
Navigating through final classes
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.
Was this article helpful?