Ade*_*lin 0 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);
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是我如何告诉模拟在前两次返回“ERROR”并在第三次返回“SUCCESS”?
标题告诉 JMock,标签告诉 JMockit
你的代码看起来像 Mockito (而不是像 JMock 或 JMockit )所以我假设你使用 Mockito 无论你在描述中写了什么......
Mockito 允许您按顺序枚举返回值或链接.then*()方法:
// 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4191 次 |
| 最近记录: |