[英]Why is Polly not retrying the exception in my unit test?
我有以下具有可重试网络调用的方法。 为特定异常指定重试策略。
public async Task<MyResponse> GetRecords(MyRequest request)
{
try
{
RetryPolicy retryPolicy = Policy.Handle<MyException>(ex => ex.ErrorCode == ErrorCode.MySpecificErrorCode)
.Retry(MAX_RETRY_COUNT, onRetry: (exception, retryCount) =>
{
log($"Retrying for {retryCount} times due to my error that I want to retry");
});
return await retryPolicy.Execute(async () =>
await OtherService.NetworkCall(request).ConfigureAwait(false))
.ConfigureAwait(false);
}
catch (Exception ex)
{
log(ex);
throw;
}
}
这是单元测试。
[TestMethod()]
public async Task TestRetry()
{
OtherServiceMock.SetupSequence(x => x.NetworkCall(It.IsAny<MyRequest>()))
.ThrowsAsync(new MyException(ErrorCode.MySpecificErrorCode, ExceptionMessage.MySpecificErrorMessage)) //this is getting thrown
.ThrowsAsync(new Exception());
MyRequest request = new MyRequest();
try
{
var response = await new MyClassMock.GetRecords(request).ConfigureAwait(false);
}
catch(Exception ex)
{
log("Event","Event");
}
}
第一个异常被抛出而不是第二个。 我已经调整了最大重试次数,它没有帮助。 我在这里做错了什么?
您的模拟设置适用于x.GetRecord
OtherServiceMock.SetupSequence(x => x.GetRecord(It.IsAny<MyRequest>()))
.ThrowsAsync(new MyException(ErrorCode.MySpecificErrorCode, ExceptionMessage.MySpecificErrorMessage)) //this is getting thrown
.ThrowsAsync(new Exception());
但是您希望 polly 重试的部分是OtherService.NetworkCall
return await retryPolicy.Execute(async () =>
await OtherService.NetworkCall(request).ConfigureAwait(false))
.ConfigureAwait(false);
您的 SetupSequence 应该是 mocking NetworkCall
OtherServiceMock.SetupSequence(x => x.NetworkCall(It.IsAny<MyRequest>()))
.ThrowsAsync(new MyException(ErrorCode.MySpecificErrorCode, ExceptionMessage.MySpecificErrorMessage)) //this is getting thrown
.ThrowsAsync(new Exception());
为了清楚起见,如果您想通过重试来装饰同步 function,那么您必须使用以下策略构建器方法之一:
Retry
,RetryForever
,WaitAndRetry
,WaitAndRetryForever
在这种情况下,策略将是RetryPolicy
,它实现了ISyncPolicy
接口。 因此,您可以调用不可等待的Execute
。
如果要通过重试来装饰异步 function,则必须使用以下策略构建器方法之一:
RetryAsync
,RetryForeverAsync
,WaitAndRetryAsync
,WaitAndRetryForeverAsync
在这种情况下,策略将是一个AsyncRetryPolicy
,它实现了IAsyncPolicy
接口。 因此,您可以调用awaitable的ExecuteAsync
。
在这里,我详细介绍了如何在这些方法变体之间进行选择: https://stackoverflow.com/a/73095879/13268855
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.