重试策略的单元测试引发异常

时间:2020-04-27 13:55:00

标签: c# unit-testing xunit polly

我正在尝试编写一个单元测试以使用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");
            });

我要做什么:

  1. 将SqlException抛出ExecuteAsync 2次
  2. 第三次返回true

实际发生的事情:

  1. 在ExecuteAsync中引发SqlException 1次
  2. 单元测试失败
  3. ExecuteAsync不会再运行2次

0 个答案:

没有答案