Mockito inOrder()

1. Overview

The Mockito.inOrder() method is employed to validate that the methods of mocked objects are invoked in a specific order. This becomes crucial when the order of operations is vital for the system's correctness. This tutorial explores the usage of Mockito.inOrder() and demonstrates its utility through a simple example.

2. Development Steps

1. Set up a new Maven project.

2. Incorporate required dependencies: Mockito and JUnit 5.

3. Develop a class (AccountService) with methods that will be tested for order of invocation.

4. Design a test class to display the usage of Mockito.inOrder().

5. Run the test cases.

6. Analyze the test outcomes.

3. Dependencies (Mockito and JUnit 5)

<!-- JUnit 5 -->
<!-- Mockito -->

4. Code Program

// Step 3: Create an AccountService class with deposit and withdraw methods
class AccountService {
    void deposit(int amount) {
        // Logic to deposit money
    void withdraw(int amount) {
        // Logic to withdraw money
// Step 4: Construct the test class for AccountService
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.inOrder;
public class AccountServiceTest {
    public void orderOfInvocationTest() {
        // Generate a mock of AccountService
        AccountService mockService = mock(AccountService.class);
        // Simulate deposit and withdraw operations on the mock
        // Use inOrder to validate the order of invocation
        InOrder inOrder = inOrder(mockService);


The orderOfInvocationTest will pass, confirming that the methods on the mock AccountService were invoked in the expected order: deposit() followed by withdraw().

Code Explanation:

1. After setting up the Mockito and JUnit 5 dependencies, we introduce a simple AccountService class with two methods: deposit and withdraw.

2. We then generate a mock of this AccountService using the Mockito mock() method.

3. We stimulate a sequence of method invocations on the mock by calling deposit(100) followed by withdraw(50).

4. With the help of Mockito.inOrder(), we create an InOrder object, which provides the mechanism to verify the sequence of method calls.

5. The InOrder object's verify() method is then used to check the order of method invocations on the mock. If any method is called out of the expected sequence, the test will fail.

5. Conclusion

The Mockito.inOrder() method is an invaluable utility when the order of method invocations is crucial to the functioning of a system. By employing inOrder, developers and testers can gain assurance about the correct sequence of operations, making it an essential tool in the Mockito toolkit.

Related Mockito Methods

Mockito mock()
Mockito spy()
Mockito when()
Mockito thenThrow()
Mockito verify()
Mockito times()
Mockito never()
Mockito any()
Mockito eq()
Mockito inOrder()
Mockito doReturn()
Mockito doThrow()
Mockito doAnswer()
Mockito timeout()
Mockito ArgumentMatchers