Search code examples
c#.net-coreintegration-testingpolly

How to write integration test for typed client in .NET


I have a .NET 7 console application that fetches data from an API.

The console application is simple and uses a "typed client", that I am writing:

services.AddSingleton<IMyTypedClient, MyTypedClient>();
services.AddHttpClient<IMyTypedClient, MyTypedClient>(client =>
    {
        client.BaseAddress = new Uri("http://www.randomnumberapi.com/api/v1.0/");
    })
    .SetHandlerLifetime(TimeSpan.FromMinutes(5))
    .AddPolicyHandler(GetRetryPolicy());

static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
    return HttpPolicyExtensions
        .HandleTransientHttpError()
        .OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
        .WaitAndRetryAsync(6, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
}

Here is the "typed client":

public class MyTypedClient : IMyTypedClient
{
    private readonly HttpClient _httpClient;

    public MyTypedClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public void GetRandomNumber()
    {
        var response = _httpClient.GetAsync("/random?min=1&max=10&count=5").Result;
        if (response.StatusCode != HttpStatusCode.OK)
        {
            throw new Exception("Failed to get random number");
        }
    }
}

The above code is inspired by MS documentation.

Question I would like to integration test the "typed client" part of the app that I am writing while developing it, but how do I create integration tests for this typed client that takes a HttpClient?


Solution

  • I ended up just doing the following helper method in my "test" fixture:

        const string baseUrl = "https://someurl";
        const string accessToken = "token";
    
        var httpClient = new HttpClient
        {
            BaseAddress = new Uri(baseUrl)
        };
    
    
        return new MyTypedClient(httpClient, accessToken);