有代码在循环中调用方法,我想测试一下该方法在2次尝试中引发异常然后返回有效值的情况。 使用JMockit,我编写以下代码:
new Expectations() {{
someService.call(anyString);
times = 2;
result = exception;
someService.call(anyString);
result = entity;
}};
在这种情况下,它someService::call
总是返回entity
。
如何为前两个呼叫返回exception
,然后在测试中返回entity
?
答案 0 :(得分:1)
与其他任何模拟API一样,以期望的顺序记录期望的每个期望结果:
new Expectations() {{
someService.call(anyString);
result = exception;
result = exception;
result = entity;
}};
答案 1 :(得分:0)
我认为是这样的:
Service someService = mock(Service.class);
when(someService(any()))
.thenThrow(new RuntimeException())
.thenThrow(new RuntimeException())
.thenReturn("foo");
应该工作