我正在尝试编写一个单元测试以使用Polly测试策略WaitAndRetryAsync 要测试该策略,我需要模拟并抛出带有某些sqlerror数字的SqlException。
我已遵循他们关于单元测试策略的文档,特别是[2b] Test policies with unit-tests, independent of consuming code
单元测试,我使用Stackoverflow问题How to throw a SqlException when needed for mocking and unit testing?创建了SqlExceptionMocker类
//Arrange
var policy = new CustomPolicyClass();
var randomSqlException = 0;
var invocations = 0;
var generatedException = SqlExceptionMocker.MakeSqlException(randomSqlException);
//Act
var result = await policy.TimeoutExceptionPolicy()
.ExecuteAsync<bool>(async () => invocations++ <= 1 ? throw generatedException : true);
//Assert
Assert.True(result);
public async Task<IAsyncPolicy> TimeoutExceptionPolicy() =>
Policy
.Handle<SqlException>(ex => errorNumberArray.Contains(ex.Number))
.WaitAndRetryAsync(3,
retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
(ex, timeSpan) =>
{
Console.WriteLine($"Exception: {ex.Message}");
Console.WriteLine($"Retrying in {timeSpan.Seconds} seconds");
});