Adelin Adelin - 1 year ago 68
Java Question

Change a mock object behavior based on invocations times with Mockito?

I am mocking an interface for submitting some objects to a remote Http service, the logic goes as follow: try to submit the object 5 times if the submission succeeds then continue to the next one otherwise try until it reaches 5 - times then discard if still fails.

interface EmployeeEndPoint {

Response submit(Employee employee);


class Response {

String status;

public Response(String status) {
this.status = status;

class SomeService {

private EmployeeEndPoint employeeEndPoint;

void submit(Employee employee) {

Response response = employeeEndPoint.submit(employee);

//put this employee in a queue and then retry 5 more time if the call succeeds then skip otherwise keep trying until the 5th.


EmployeeEndPoint employeeEndPoint;

public void shouldStopTryingSubmittingEmployeeWhenResponseReturnsSuccessValue() {
//I want the first

Employee employee
= new Employee();
when(employeeEndPoint.submit(employee)).thenReturn(new Response("ERROR"));
when(employeeEndPoint.submit(employee)).thenReturn(new Response("ERROR"));
when(employeeEndPoint.submit(employee)).thenReturn(new Response("SUCCESS"));
//I want to verify that when call returns SUCCESS then retrying stops !

// call the service ..


Now the question is how do I tell the mock to return "ERROR" the first two times and to return "SUCCESS" on the third time?

Answer Source

Caption tell JMock, tag tells JMockit

Your code looks like Mockito (and not like JMock nor JMockit) so I assume your using Mockito despite what you wrote in your description...

Mockito lets you either enumerate the return values in order or chain the .then*() methods:

// either this
   new Response("ERROR"),
   new Response("ERROR"),
   new Response("SUCCESS") // returned at 3rd call and all following
// or that
    .thenReturn(new Response("ERROR"))
    .thenReturn(new Response("ERROR"))
    .thenReturn(new Response("SUCCESS"));// returned at 3rd call and all following
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download