Home >Java >javaTutorial >How Can I Mock a Final Class in Mockito?
Mocking Final Classes with Mockito
Problem:
You have a final class that you want to mock in a JUnit test. However, Mockito appears to have limitations in mocking final classes.
Detailed Question:
Consider the following example code:
Java
public final class RainOnTrees { public void startRain() { // some code here } }
In another class:
Java
public class Seasons { RainOnTrees rain = new RainOnTrees(); public void findSeasonAndRain() { rain.startRain(); } }
In the JUnit test class for Seasons.java, you want to mock the RainOnTrees class. How can you achieve this using Mockito?
Answer:
Beginning with Mockito v2, it has become possible to mock final classes. To enable this functionality, add the following to your Gradle file:
Java
testImplementation 'org.mockito:mockito-inline:2.13.0'
Note that mocking final classes was not feasible with Mockito v1. As mentioned in the Mockito FAQ:
"Cannot mock final classes"
For more information on the limitations of Mockito, refer to the official documentation.
The above is the detailed content of How Can I Mock a Final Class in Mockito?. For more information, please follow other related articles on the PHP Chinese website!