What is the difference between mockito-core and mockito-inline?
In my project, we already have the mockito-core
dependency. However, I need to stub a static method, which requires adding the mockito-inline
dependency.
I want to understand the difference between mockito-core
and mockito-inline
. Can they coexist in the same project?
Simply replace or add mockito-inline to your project dependencies to enable mocking of static, final, and private methods. mockito-inline extends mockito-core, so they can coexist in the same project.
Example:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.x.x</version>
<scope>test</scope>
</dependency>
Why it works: This approach ensures that you can mock static methods and other special cases that mockito-core doesn’t support.
Stick to mockito-core and Refactor Code to Avoid Mocking Static Methods:
If mocking static methods is not a core requirement, you can refactor your code to make it more testable by avoiding static methods. Use dependency injection or wrapper classes to facilitate easier mocking.
Example:
// Refactor static method to instance method
public class SomeClass {
public String instanceMethod() {
return "Hello";
}
}
For legacy projects that need to mock static, final, or private methods, consider using PowerMock in conjunction with Mockito. While PowerMock is less commonly used with newer Mockito versions, it still provides comprehensive support for these advanced cases.
Example:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.x.x</version>
<scope>test</scope>
</dependency>
Why it works: PowerMock can mock static methods, constructors, and final methods, providing an alternative solution to mockito-inline.