简体   繁体   English

如何在 .NET 中为类型化客户端编写集成测试

[英]How to write integration test for typed client in .NET

I have a .NET 7 console application that fetches data from an API.我有一个 .NET 7 控制台应用程序,它从 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 .上面的代码是受MS 文档的启发。

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 ?问题我想集成测试我在开发应用程序时编写的应用程序的“类型化客户端”部分,但是如何为这个采用HttpClient的类型化客户端创建集成测试?

If you want to 'just' test the "typed client" you should not connect it to the external service during the test.如果你想“只是”测试“类型化的客户端”,你不应该在测试期间将它连接到外部服务。 You would have to provide a mock for the HttpClient in this case and inject that during the tests.在这种情况下,您必须为 HttpClient 提供模拟,并在测试期间注入它。 This mock would have to return predictable results.这个模拟必须返回可预测的结果。

If you do want to use the external service, the test becomes very brittle because you cannot predict and therefore check if the results are correct.如果您确实想使用外部服务,测试会变得非常脆弱,因为您无法预测并检查结果是否正确。

In both cases testing will be hard because the typed client does not return anything, this makes is impossible to check the results.在这两种情况下,测试都会很困难,因为类型化的客户端不返回任何内容,这使得无法检查结果。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM