0

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);

        if(response.status=="ERROR"){
            //put this employee in a queue and then retry 5 more time if the call succeeds then skip otherwise keep trying until the 5th.
        }
    }


}

@Mock
EmployeeEndPoint employeeEndPoint;


@Test
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 ..


    verify(employeeEndPoint,times(3)).submit(employee);
}

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?

Adelin
  • 18,144
  • 26
  • 115
  • 175

1 Answers1

5

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
when(employeeEndPoint.submit(employee)).thenReturn(
   new Response("ERROR"),
   new Response("ERROR"),
   new Response("SUCCESS") // returned at 3rd call and all following
);
// or that
when(employeeEndPoint.submit(employee))
    .thenReturn(new Response("ERROR"))
    .thenReturn(new Response("ERROR"))
    .thenReturn(new Response("SUCCESS"));// returned at 3rd call and all following
Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51