question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unit test code that contains AsyncCircuitBreakerPolicy

See original GitHub issue

Summary: 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:closed
  • Created 3 years ago
  • Reactions:2
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
ben-burtoncommented, Sep 4, 2020

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

public interface ICircuitBreaker : IAsyncPolicy, ICircuitBreakerPolicy
{ }
0reactions
github-actions[bot]commented, Jul 20, 2023

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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to mock AsyncPolicyWrap or AsyncPolicy in .Net Core ...
I have a code like this (I have to test a repo, you'll see the code below) public class SomeClass { public AsyncPolicyWrap...
Read more >
Unit testing C# code in .NET Core using dotnet test and xUnit
Learn unit test concepts in C# and .NET Core through an interactive experience ... The new class library will contain the code to...
Read more >
Unit Testing and Coding: Why Testable Code Matters
In this unit testing tutorial, I intend to demonstrate that unit tests are quite easy; the real problems that complicate unit testing, and...
Read more >
Unit Testing - should / how should I write tests to cover new ...
Call verification makes test code brittle. Code can be refactored in such a way that it is still correct, but break call verification...
Read more >
Unit Testing: Definition, Examples, and Critical Best Practices
The objective of a unit test is to test an entity in the code, ensure that it is coded correctly with no errors,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found