Introduction
When mocking specific methods using Mockito sometimes, we need to check the number of calls made on a particular method. These help us in making sure that the methods in use are restricted with the number of times they are called.
In this blog, we will learn about the expecting calls that help us in mitigating the above problem and thus add the functionality of maintaining the number of calls made using Mockito for mocking.
Expecting Calls
When we use mockito, it provides us with a special check on the number of calls that are made by a particular method. For example we have an interface that we must make sure is called only once, we can use these methods to check the same.
Example
First we create an interface that contains all the methods that we want to check the order for.
Program
public interface CalculatorService {
public double add(double input1, double input2);
public double subtract(double input1, double input2);
public double multiply(double input1, double input2);
public double divide(double input1, double input2);
}Then we need to create a java class that can represent the MathApplication to contain our methods.
Program
public class MathApplication{
private CalculatorService;
public void setCalculatorService(CalculatorService calcService){
this.calcService = calcService;
}
}
public double add(double input1, double input2){
return calcService.add(input1,input2);
}Next we need to mock the behaviour of the above method so as to create our test even though the actual functionality is not ready.
when(calcService.add(10.0, 20.0).thenReturn(30.0));Now we can check whether the add method is called a particular number of times using the below example.
verify(calcService.times(2)).add(10.0,20.0); //simply executing the tests gives us the result as True.




