I am trying to write a unit test to test the policy WaitAndRetryAsync using Polly To test the policy I need to simulate and throw a SqlException with certain sqlerror numbers.
I have followed their documentation on unit testing policies, specifically [2b] Test policies with unit-tests, independent of consuming code
Unit Test, I used Stackoverflow question How to throw a SqlException when needed for mocking and unit testing? to create class 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");
});
What I am trying to do:
- Throw SqlException in ExecuteAsync 2 times
- 3rd time return true
What actually happens:
- Throws SqlException in ExecuteAsync 1 time
- Unit test fails
- ExecuteAsync does not rerun 2 more times