mockito验证lambda被调用n次

cedebl8k  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(431)

我需要测试lambda函数是否从服务示例调用了n次。
我有一个与存储库交互的服务类,当从存储库中检索数据时发生错误,服务应该重试,直到达到最大重试次数,因此我实现了如下:

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() 从来没有人打过电话。

cs7cruho

cs7cruho1#

我终于找到了不使用 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();
    }

}

}

相关问题