0

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:

  1. Throw SqlException in ExecuteAsync 2 times
  2. 3rd time return true

What actually happens:

  1. Throws SqlException in ExecuteAsync 1 time
  2. Unit test fails
  3. ExecuteAsync does not rerun 2 more times
RealYlem
  • 15
  • 4
  • I've read it over several times but it's hard to understand. What is the policy you are trying to test? It's not shown. What is the failure? I realize the information is likely in there but it's not clear. – Scott Hannen Apr 27 '20 at 15:48
  • Please add your CustomPolicyClass source code – tom redfern Apr 27 '20 at 18:28
  • I tried to make the question abit more clear, maybe it's better now? the problem is that after throwing SqlException it should retry to run ExecuteAsync() 2 more times – RealYlem Apr 27 '20 at 21:28
  • 1
    A possible reason for the policy not handling an exception is that the exception filter does not match the exception thrown. What happens if you set a breakpoint on the filter lambda (the `errorNumberArray.Contains(ex.Number)` part only, not the whole `.Handle<>(...)` clause), then step-debug the test to see exactly the exception thrown and whether/why the filter does/doesn't match it? If that doesn't show the reason, consider adding to the q a [small reproducible example](https://stackoverflow.com/help/minimal-reproducible-example), perhaps as a [DotNetFiddle](https://dotnetfiddle.net/). – mountain traveller May 02 '20 at 08:39
  • @mountaintraveller you're totally right, that was the actual problem. In my policy class I was looking for Microsoft.Data.SqlClient exception but in the unit test i actually sent a System.Data.SqlClient exception.. – RealYlem May 02 '20 at 15:58

0 Answers0