Harish
Harish

Reputation: 726

Mockito - Verify a method is called twice with two different params

I have to verify the behavior on the following method:

public void saveRequestAndResponse(request, response, additionalInfo) {
    // some processing with additionalInfo
    dao.save(request);
    dao.save(response);
}

In my test class:

ArgumentCaptor<com.ws.Request> request = ArgumentCaptor.forClass(com.ws.Request.class);
Mockito.verify(dao, Mockito.times(1)).save(request.capture());

ArgumentCaptor<com.ws.Response> response = ArgumentCaptor.forClass(com.ws.Response.class);
Mockito.verify(dao, Mockito.times(1)).save(response.capture());

And the DAO method:

@Transactional
Public <T> T save(final T it) {
    saveOrUpdate(it);
}

Error received:

org.mockito.exceptions.verification.TooManyActualInvocations: 
dao.save(<Capturing argument>);
Wanted 1 time:
-> at com.ws.testclass(TestClass.java:296)
But was 2 times:
-> at com.ws.mainclass.lambda$saveRequestAndResponse$78(MainClass.java:200)
-> at com.ws.mainclass.saveRequestAndResponse(MainClass.java:205)

The save() method in my DAO class uses the type parameter T.

How do I verify two invocations on dao.save(type) method with two different types such as Request and Response?

Upvotes: 5

Views: 5450

Answers (2)

Daniel
Daniel

Reputation: 4549

What you want is in order verification. From the documentation:

// A. Single mock whose methods must be invoked in a particular order
 List singleMock = mock(List.class);

 //using a single mock
 singleMock.add("was added first");
 singleMock.add("was added second");

 //create an inOrder verifier for a single mock
 InOrder inOrder = inOrder(singleMock);

 //following will make sure that add is first called with "was added first, then with "was added second"
 inOrder.verify(singleMock).add("was added first");
 inOrder.verify(singleMock).add("was added second");

Upvotes: 4

Marco
Marco

Reputation: 587

You can use something like this:

ArgumentCaptor<Object> parameters = ArgumentCaptor.forClass(Object.class);
Mockito.verify(dao, Mockito.times(2)).save(parameters.capture());
List<Object> values= parameters.getAllValues();
com.ws.Request req= (com.ws.Request) values.get(0);
com.ws.Response res= (com.ws.Respons) values.get(1);
//Validations

Upvotes: 5

Related Questions