3

我有代码向客户端添加一个命名HttpClientServiceCollection添加一个DelegatingHandler。示例代码:

public class MyDelegatingHandler : DelegatingHandler
{
    // ...
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureServices((hostContext, services) =>
        {
            services.AddHttpClient("MyClient")
                .AddHttpMessageHandler(provider => new MyDelegatingHandler());
        });

编写单元测试时,如何验证DelegatingHandler添加的实现是MyDelegatingHanlder

4

1 回答 1

2

此信息存储在HttpClient. 你可以理解它,但它有点不正统。所以,你可能感兴趣也可能不感兴趣,但我会把它扔在那里,以防你:

public static class HttpClientExtensions
{
    public static bool ContainsDelegatingHandler<TDelegatingHandler>(
        this HttpClient httpClient) where TDelegatingHandler: DelegatingHandler
    {
        if(httpClient == null)
        {
            throw new ArgumentNullException(nameof(httpClient));
        }

        var internalHandlerField = typeof(HttpMessageInvoker).GetField(
            "_handler", BindingFlags.NonPublic | BindingFlags.Instance);
        if(internalHandlerField == null)
        {
            throw new InvalidOperationException(
                "_handler no longer exists as a private instance field of HttpClient");
        }

        // run down the chain of delegating handlers until there are no more
        var delegatingHandler = internalHandlerField.GetValue(httpClient) as DelegatingHandler;
        while (delegatingHandler != null)
        {
            if(delegatingHandler.GetType() == typeof(TDelegatingHandler))
            {
                return true;
            }
            delegatingHandler = delegatingHandler.InnerHandler as DelegatingHandler;
        }

        return false;
    }
}

要进行测试,您首先必须HttpClient使用工厂创建一个:

var httpClient = httpClientFactory.CreateClient("MyClient");

然后通过扩展运行它:

if(!httpClient.ContainsDelegatingHandler<MyDelegatingHandler>())
{
    throw new Exception(
        "HttpClient with name 'MyClient' does not contain " +
        $"{nameof(MyDelegatingHandler)} delegating handler.");
}
于 2020-09-01T00:00:12.760 回答