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:
Answer from user180100 on Stack OverflowWhat are the limitations of Mockito
Needs java 1.5+
Cannot mock final classes
...
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
...
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.MockMakercontaining a single line:mock-maker-inlineAfter 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!
Finally fixed, both in command line and IDE (IntelliJ IDEA). There are two different warnings, so the fix comes in two parts, you can try each argument on its own to see the effect:
Copy<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
-javaagent:${settings.localRepository}/org/mockito/mockito-core/${mockito.version}/mockito-core-${mockito.version}.jar
-Xshare:off
</argLine>
</configuration>
</plugin>
No need for -XX:+EnabledDynamicAgentLoading or maven-dependency-plugin.
All the credit goes to this and this answers.
Also, take a look at this to understand why some configuration might only work for the build tool or the IDE. So you should use a neutral configuration, otherwise you will need a different configuration for each.
For gradle projects you can try this. Tested on Intellij only.
Copytest {
jvmArgs "-javaagent:${configurations.testRuntimeClasspath.find { it.name.contains('mockito-core') }}", '-Xshare:off'
...
}