【问题标题】:Spring retry with retryTemplate - unit tests使用 retryTemplate 进行春季重试 - 单元测试
【发布时间】:2018-10-11 22:10:43
【问题描述】:

我正在使用 retryTemplate,但我不知道如何为此进行单元测试。有人可以帮忙吗?

我有这段代码(例如),我想测试一下,我第一次调用 Card.create 失败,但第二次成功。

@Autowired
private RetryTemplate retryTemplate; 

public String registerCard(final String cardNumber) throws ApiException {  
    final Card response = retryTemplate.execute(new RetryCallback<Card, ApiException>() {
        @Override public Card doWithRetry(RetryContext retryContext) throws ApiException {
          return Card.create(map);
        }
     }) ;
     return response.get("number").toString();
}

RetryTemplate 的 maxAttemps = 2 和 backOff = 1500。

最好的问候。

【问题讨论】:

    标签: spring-boot spring-retry retrytemplate


    【解决方案1】:

    在您的测试中,将RetryListener 实现添加到RetryTemplate;使用监听器上的方法来监控重试活动。

    public interface RetryListener {
    
        /**
         * Called before the first attempt in a retry. For instance, implementers
         * can set up state that is needed by the policies in the
         * {@link RetryOperations}. The whole retry can be vetoed by returning
         * false from this method, in which case a {@link TerminatedRetryException}
         * will be thrown.
         *
         * @param <T> the type of object returned by the callback
         * @param <E> the type of exception it declares may be thrown
         * @param context the current {@link RetryContext}.
         * @param callback the current {@link RetryCallback}.
         * @return true if the retry should proceed.
         */
        <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback);
    
        /**
         * Called after the final attempt (successful or not). Allow the interceptor
         * to clean up any resource it is holding before control returns to the
         * retry caller.
         * 
         * @param context the current {@link RetryContext}.
         * @param callback the current {@link RetryCallback}.
         * @param throwable the last exception that was thrown by the callback.
         * @param <E> the exception type
         * @param <T> the return value
         */
        <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwable throwable);
    
        /**
         * Called after every unsuccessful attempt at a retry.
         * 
         * @param context the current {@link RetryContext}.
         * @param callback the current {@link RetryCallback}.
         * @param throwable the last exception that was thrown by the callback.
         * @param <T> the return value
         * @param <E> the exception to throw
         */
        <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable);
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多