Verify the order in which a method have been called with different arguments

I would like to verify that my method is invoked with different arguments in a fixed order. I've tried this:

org.mockito.Mockito.verify(mock).myMethod(arg1);
org.mockito.Mockito.verify(mock).myMethod(arg2);
//was myMethod called with arg1 before it was called with arg2?

but that does not take order into account. Is there an easy way to do this?

Upvotes: 2

Views: 3694

Answers (2)

Rangi Lin
Rangi Lin

Reputation: 9451

Mockito provide InOrder to verify call in orders

take a look this document : Verification in order

example :

MyClass mock = mock(MyClass.class);
InOrder order = inOrder(mock);

order.verify(mock).myMethod("first");
order.verify(mock).myMethod("second");

last two line will verify mock object been called in that order and arguments.

Upvotes: 7

Marcin Cylke
Marcin Cylke

Reputation: 2066

You could use ArgumentCaptor. Here is a snippet from Mockito Javadoc:

ArgumentCaptor<Person> peopleCaptor = ArgumentCaptor.forClass(Person.class);
   verify(mock, times(2)).doSomething(peopleCaptor.capture());

   List<Person> capturedPeople = peopleCaptor.getAllValues();
   assertEquals("John", capturedPeople.get(0).getName());
   assertEquals("Jane", capturedPeople.get(1).getName());

Upvotes: 3

Related Questions