gpt4 book ai didi

java - 使用 Mockito 根据调用时间更改模拟对象行为?

转载 作者:行者123 更新时间:2023-12-01 09:17:04 24 4
gpt4 key购买 nike

我正在模拟一个用于向远程Http服务提交一些对象的接口(interface),逻辑如下:如果提交成功,则尝试提交对象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”?

最佳答案

Caption tell JMock, tag tells 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

关于java - 使用 Mockito 根据调用时间更改模拟对象行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40469042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com