如何解决Mockito验证lambda被称为n次
我需要测试一个lambda函数是否从服务实例中被调用了n次。
我有一个与存储库交互的Service类,当从存储库检索数据时发生错误时,该服务应重试,直到达到最大重试次数为止,因此我实现了以下操作:
interface Repository {
Collection<String> getData();
}
public class RetryHelper<T> {
private Integer retries;
public RetryHelper(Integer retries) {
this.retries = retries;
}
public interface Operation<T> {
T doIt() throws Exception;
}
public T doWithRetry(Operation<T> operation) throws Exception {
int remainRetries = retries;
do {
try {
return operation.doIt();
} catch (Exception e) {
if (remainRetries == 0) {
throw e;
}
//TODO: wait before retry
remainRetries--;
}
} while (true);
}
}
class Service {
@Inject
Repository repo;
private final RetryHelper<Collection<String>> retryHelper;
public Collection<String> callService() {
try {
Collection<String> res = retryHelper.doWithRetry(() ->
repo.getData());
return res;
} catch (Exception e) {
throw (CustomException) e;
}
}
}
我需要使用Mockito测试发生错误时repo.getData()
被称为n次。我可以更改Service
代码和RetryHelper
,因此可以提出建议。
我已尝试按照以下教程和文档进行测试:
public class ServiceTest {
@Inject
Service service;
@InjectMock
Repository repository;
@InjectMock
RetryHelper<Collection<String>> retryHelper;
@Captor
ArgumentCaptor<RetryHelper.Operation<Collection<String>>> operation;
@BeforeEach
void init_mocks() {
MockitoAnnotations.openMocks(this);
}
@Test
void shouldRetryIfDataQueryFailsForNonFatalError() throws Exception {
when(repository.getData())
.thenThrow(new RuntimeException("Runtime Exception"));
service.callService();
verify(retryHelper).doWithRetry(operation.capture());
verify(repository,times(2)).getData();
}
}
测试失败,并显示一条消息,即从未调用getData()
。
解决方法
我终于找到了不使用Captor
public class ServiceTest {
@Inject
Service service;
@InjectMock
Repository repository;
@Inject
RetryHelper<Collection<String>> retryHelper;
@Test
void shouldRetryIfDataQueryFailsForNonFatalError() throws Exception {
when(repository.getData())
.thenThrow(new RuntimeException("Runtime Exception"));
try {
service.callService();
} catch(Exception e) {
verify(repository,times(2)).getData();
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。