How to mock a final class with mockito How to mock a final class with mockito java java

How to mock a final class with mockito


Mockito 2 now supports final classes and methods!

But for now that's an "incubating" feature. It requires some steps to activate it which are described in What's New in Mockito 2:

Mocking of final classes and methods is an incubating, opt-in feature. It uses a combination of Java agent instrumentation and subclassing in order to enable mockability of these types. As this works differently to our current mechanism and this one has different limitations and as we want to gather experience and user feedback, this feature had to be explicitly activated to be available ; it can be done via the mockito extension mechanism by creating the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker containing a single line:

mock-maker-inline

After you created this file, Mockito will automatically use this new engine and one can do :

 final class FinalClass {   final String finalMethod() { return "something"; } } FinalClass concrete = new FinalClass();  FinalClass mock = mock(FinalClass.class); given(mock.finalMethod()).willReturn("not anymore"); assertThat(mock.finalMethod()).isNotEqualTo(concrete.finalMethod());

In subsequent milestones, the team will bring a programmatic way of using this feature. We will identify and provide support for all unmockable scenarios. Stay tuned and please let us know what you think of this feature!


Mocking final/static classes/methods is possible with Mockito v2 only.

add this in your gradle file:

testImplementation 'org.mockito:mockito-inline:2.13.0'

This is not possible with Mockito v1, from the Mockito FAQ:

What are the limitations of Mockito

  • Needs java 1.5+

  • Cannot mock final classes

...


add this in your build file:

testImplementation 'org.mockito:mockito-inline:2.13.0'
<dependency>    <groupId>org.mockito</groupId>    <artifactId>mockito-inline</artifactId>    <version>2.13.0</version>    <scope>test</scope></dependency>

this is a configuration to make mockito work with final classes

If you faced the Could not initialize inline Byte Buddy mock maker. (This mock maker is not supported on Android.)Add the Byte Buddy dependency to your build.gradle file:

testImplementation 'net.bytebuddy:byte-buddy-agent:1.10.19'

src: https://mvnrepository.com/artifact/net.bytebuddy/byte-buddy