TUnit icon indicating copy to clipboard operation
TUnit copied to clipboard

TUnit0023 - Incorrect warning for typed HttpClient

Open vfrz opened this issue 9 months ago • 3 comments

I have a typed HttpClient class like that:

public class CustomApiClient(HttpClient httpClient) : ICustomApiClient
{
// Methods
}

Registered in DI like that:

services.AddHttpClient<ICustomApiClient, CustomApiClient>();

And in my test class I'm having the following warning: Warning TUnit0023 : CustomApiClient should be disposed within a clean up method because it has a HttpClient in the constructor. When using typed HttpClient in .NET you should not dispose the HttpClient yourself so I have no need to make ICustomApiClient implementing IDisposable.

I'm not sure of the expected behavior here, but shouldn't this warning only appear if the class itself implement IDisposable?

vfrz avatar May 09 '25 18:05 vfrz

How is this passed to your test class?

thomhurst avatar May 18 '25 20:05 thomhurst

@vfrz Could you show how your test class receives this please?

thomhurst avatar May 24 '25 13:05 thomhurst

Here is a snipped of my code:

public abstract class ProviderTests
{
    protected readonly CustomApiClient CustomApiClient;

    protected ProviderTests()
    {
        var testEnv = Environment.GetEnvironmentVariable("TEST_ENV");
        var configuration = new ConfigurationBuilder()
            .AddJsonFile(testEnv is null ? "testsettings.json" : $"testsettings.{testEnv}.json")
            .Build();
        var settings = configuration.GetSection(ApiSettings.Section).Get<ApiSettings>()!;

        CustomApiClient = new CustomApiClient(new HttpClient
        {
            BaseAddress = new Uri(settings.Url)
        });
    }
}

This is a base class I use for my other tests. In the context of the test it could make sense to dispose it since I create the HttpClient manually, but I don't want to change my code just for testing purposes in that case.

vfrz avatar May 26 '25 21:05 vfrz

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.

github-actions[bot] avatar Jun 26 '25 00:06 github-actions[bot]

This issue was closed because it has been stalled for 5 days with no activity.

github-actions[bot] avatar Jul 01 '25 00:07 github-actions[bot]