使用Mockito根据调用次数更改模拟对象行为?

时间:2016-11-07 15:41:28

标签: java unit-testing mocking mockito

我正在嘲笑一个用于向远程Http服务提交一些对象的接口,逻辑如下:如果提交成功则尝试提交对象5次,然后继续尝试下一个,否则尝试直到达到5次如果仍然失败则丢弃。

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

现在的问题是如何告诉模拟器在前两次返回“ERROR”并在第三次返回“SUCCESS”?

1 个答案:

答案 0 :(得分:1)

  

标题告诉JMock,标签告诉JMockit

你的代码看起来像Mockito(而不是像JMock和JMockit)所以我假设你使用Mockito,尽管你在你的描述中写了...

Mockito允许您按顺序枚举返回值或链接cd.fill = openpyxl.styles.PatternFill('solid', openpyxl.styles.colors.GREEN) 方法:

.then*()