How to Mock Variables for Interfaces and Casts in Java
One common issue when writing JUnit tests is how to create a mock when the variable is an an interface / implementation or a casting.
For example, in the case of casting:
public PaymentGateway {
void refund(SomePaymentProcessor processor);
processor = new PaymentProcessorImpl(); //concrete implementation
processor = (SomeOtherProcessor) processor; //casting
}
The variable processor is casted to SomeOtherProcessor. That's why when you create a mock with it, you have to cover both SomePaymentProcessor and SomeOtherProcessor like this:
processor = mock(SomePaymentProcessor.class, withSettings().extraInterfaces(PaymentProcessorImpl.class, SomeOtherProcessor.class));
To add the extra classes PaymentProcessorImpl and SomeOtherProcessor we have used the additional Mockitor method withSettings().extraInterfaces()
. In Java, withSettings().extraInterfaces()
is a method that is used in conjunction with the Mockito library. This method allows you to specify additional interfaces that you want to mock along with the class you are mocking.
In summary, you would use withSettings().extraInterfaces()
when you want to mock an object that implements multiple interfaces, and you want to specify all of these interfaces when creating the mock object.