Skip to content

Verifying method call order

Contents

We could verify that thefoo()method is called before authenticateUser() method:

java
// ...
InOrder inOrder = inOrder(authenticatorMock);
inOrder.verify(authenticatorMock).foo();
inOrder.verify(authenticatorMock).authenticateUser(username, password);
// ...

The inOrder method in Mockito is used to verify that interactions with mocks happened in a specific sequence. It’s especially useful when the order of method calls matters for the behavior you’re testing.

Note:

  • You can include multiple mocks in a single inOrder to verify interleaved calls across different objects.
  • Only the verified calls are checked for order; unverified calls don’t affect the check.
  • Useful for testing side effects, workflows, or sequences of operations in your class.

Example 1

java
List<String> list1 = mock(List.class);
List<String> list2 = mock(List.class);

list1.add("a");
list2.add("b");
list1.add("c");

InOrder inOrder = inOrder(list1, list2);

// Verify calls in exact order
inOrder.verify(list1).add("a");
inOrder.verify(list2).add("b");
inOrder.verify(list1).add("c");
  • This test passes because the calls match the verified sequence.
  • If list1.add("c") happened before list2.add("b"), the verification would fail!

Example 2

Here the java.util.Set interface is used as the test target. First create the mock Set by calling the org.mockito.Mockito.mock() method and passing the Set class to it as a parameter.

java
Set mockSet = mock(Set.class);

First call two methods (addAll() and clear()) of the Set class on this mock object as shown below:

java
mockSet.addAll(toAdd);
mockSet.clear();

Then verify that these methods have been called:

java
verify(mockSet).addAll(toAdd); 
verify(mockSet).clear();

This verifies certain behaviour happened once.

Argument passed are compared using equals() method. Below is the snippet of the full method:

java

@Test
public void verifyInteractions() {
	Set mockSet = mock(Set.class);
	Set<String> toAdd = new HashSet<String>();
	
	mockSet.addAll(toAdd);
	mockSet.clear();
	
	verify(mockSet).addAll(toAdd);
	verify(mockSet).clear();
}

© 2023-2025 Maduranga Kannangara. Feel free to use or share this content. Attribution is appreciated but not required.