Unit test code that contains AsyncCircuitBreakerPolicy
See original GitHub issueSummary: What are you wanting to achieve? Unit test code with circuit breaker policy
What code or approach do you have so far?
Let be that I’m registering policy with this snippet
var policy = Policy
.Handle<HttpRequestException>()
.CircuitBreakerAsync(
exceptionsAllowedBeforeBreaking: 2,
durationOfBreak: TimeSpan.FromMinutes(1)
);
services.AddTransient(_ => policy);
I can register it also with services.AddTransient<ICircuitBreakerPolicy, AsyncCircuitBreakerPolicy>(_ => policy);
, but then I need to cast it to AsyncCircuitBreakerPolicy
. It works for app, but doesn’t for unit test (missing ExecuteAsync()
in ICircuitBreakerPolicy
).
My code that I would like to cover by unit tests
ctor(AsyncCircuitBreakerPolicy breaker, ...) { ... }
var url = $"{_options.Value.ApiUrl}?some-query";
HttpResponseMessage response = null;
try
{
if (_breaker.CircuitState == CircuitState.Open)
{
return null;
}
response = await _breaker.ExecuteAsync((token) => _client.GetAsync(url, token), cancellationToken);
}
catch (BrokenCircuitException) { }
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to make request to '{Url}'", url);
}
There is no way to mock both ICircuitBreakerPolicy
(which has CircuitState
) and IAsyncPolicy
(which has ExecuteAsync()
). Or I’m missing something.
The issue could be that there is no combined interface (ICircuitBreakerPolicy with state and IAsyncPolicy with execute action) that I can inject and later on mock in unit test.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:2
- Comments:7 (3 by maintainers)
Top GitHub Comments
I also tried injecting ICircuitBreakerPolicy so I can get to the CircuitState and I am casting it to IAsyncPolicy to call execute. This presents the same problem trying to unit test. I’m not sure if this is the right approach? Is there a single interface I can inject that will allow me to do both the execution and inspect the circuit state
Edit: As a workaround I have created my own interface derived from both interfaces and used this one to mock and inject into my code, this seems to work ok
This issue is stale because it has been open for 60 days with no activity. It will be automatically closed in 14 days if no further updates are made.