Verification
Here we will be verifying using the Inorder object and verify method.
Syntax
//create an inOrder verifier for the mocks
InOrder inOrder = Mockito.inOrder(mock1, mock2);
//following will make sure that add is first called then subtract is called.
inOrder.verify(mock1).firstMethod();
inOrder.verify(mock2).secondMethod(Params1, Params2);

You can also try this code with Online Java Compiler
Run Code
Example
First we create an interface that contains all the methods that we want to check the order for.
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);
}

You can also try this code with Online Java Compiler
Run Code
Then we just mock the methods we need to test in the subsequent tests.
public void pretest(){
calcService = mock(CalculatorService.class);
}
public void mock(){
//first we add a behaviour to mock the methods
when(calcService.add(20.0,10.0)).thenReturn(30.0);
when(calcService.subtract(20.0,10.0)).thenReturn(10.0);
//then we test the functionalities
Assert.assertEquals(calcService.add(20.0,10.0),30.0);
Assert.assertEquals(calcService.subtract(20.0,10.0),10.0);
//create a verifier using Inorder for the mocks
Inorder inOrder = inOrder(calcService);
//this ensures a verification of the order
inOrder.verify(calcService).subtract(20.0,10.0);
inOrder.verify(calcService).add(20.0,10.0);
}

You can also try this code with Online Java Compiler
Run Code
FAQs
1. Difference between verifyNoMoreInteraction and verifyNoInteractions?
Ans: verifyNoMoreInteractions checks that no interactions is left for verification while verifyNoInteractions checks that no interactions happened on given mocks.
2. Can we use Jest for verifying in React?
Ans: Yes, Jest can be used for React along with many other frameworks.
3. Can I mock private methods?
Ans: When private methods are asserted from a standpoint of testing, these methods do not exist as they are not accessible to the test suite.
Key Takeaways
In this blog, we discussed how we can verify the order of the method calls using Inorder Object and verify method.
You may want to learn more about other mocking and it’s need here.
Learning never stops, and to feed your quest to learn and become more skilled, head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!
Happy Learning!