Elad Benda
Elad Benda

Reputation: 36654

how to assert orders of calls to one single mock?

I want to write a junit test with mockito

say this is my mock:

IServerApi routingServerApi = mock(ServerApi.class);
        when(routingServerApi.sendRequest(anyString(), eq("request1"))).thenReturn(myObj1);
        when(routingServerApi.sendRequest(anyString(), eq("request2"))).thenReturn(myObj2);

I want to verify that sendRequest is called with request1 just before it's called with request2 (and no other invocation between them).

How can i do this?

I have seen this SOF question,

but I want to verify order of calls to just one mock, not two.

This syntax doesn't work for me (compilation error when initing inOrder())

InOrder inOrder = inOrder(mockRoutingServerApi);

inOrder.verify(mockRoutingServerApi).sendRtUpdates(time1, ImmutableList.of("update1"));
inOrder.verify(mockRoutingServerApi).sendRoutingRequest("request1");
inOrder.verify(mockRoutingServerApi).sendRtUpdates(time1, ImmutableList.of("update2"));
inOrder.verify(mockRoutingServerApi).sendRoutingRequest("request2");

It doesn't recognize inOrder()

enter image description here

Some commented I can use ArgumentCaptor but I couldn't see how.

Upvotes: 2

Views: 498

Answers (2)

Lloyd Beech
Lloyd Beech

Reputation: 1

I had a similar problem to this. The issue may be that you have to import both the InOrder class AND the inOrder method ie;

import org.mockito.InOrder;
import static org.mockito.Mockito.inOrder;

The method should then be recognised if you add the second import above.


Another way to do this (which is doing the same thing really) is import

import org.mockito.Mockito;

and call the method from the class ie

InOrder inOrder = Mockito.inOrder(mockRoutingServerApi);

Hope this helps!

Upvotes: 0

Sergii Bishyr
Sergii Bishyr

Reputation: 8641

ArgumentCaptor can be used instead of InOrder for checking received values.

ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(mockRoutingServerApi, times(2)).sendRoutingRequest(captor.capture());

And then you can check waht is passed to sendRoutingRequest

captor.getAllValues() //Should be a List with values {"request1", "request2"}

This looks more like inventing a wheel since Mockito supports InOrder.verify. Make sure you have a static import for Mockito. Otherwise try Mockito.inOrder(routingServerApi).

Upvotes: 2

Related Questions