Mocking Private or Final Methods/Classes with Mockito
When working with testing, mocking final classes or methods is a common challenge. Mockito, a popular mocking framework, traditionally faced limitations in this aspect. However, with the release of Mockito v2, this obstacle has been overcome.
To mock a final class with Mockito v2, follow these steps:
Include Mockito v2 in Gradle:
testImplementation 'org.mockito:mockito-inline:2.13.0'
Mock the Class Directly:
// Given FinalClass finalClass = mock(FinalClass.class);
Note that you do not need to declare the @Mock annotation, as in older Mockito versions.
Limitations of Mockito v1:
As mentioned in the Mockito FAQ, Mockito v1 has limitations when it comes to mocking final classes. This is because final classes cannot be dynamically generated during runtime, a requirement for mocking.
What are the limitations of Mockito ... Cannot mock final classes
The above is the detailed content of How Can I Mock Final Classes and Methods with Mockito?. For more information, please follow other related articles on the PHP Chinese website!