22

如何对自定义 DelegatingHandler 进行单元测试?我有以下内容,但它抱怨 innerHandler 未设置。

var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://foo.com");
var handler = new FooHandler()
{
    InnerHandler = new FooHandler() 
};

var invoker = new HttpMessageInvoker(handler);
var result = await invoker.SendAsync(httpRequestMessage, new CancellationToken());

Assert.That(result.Headers.GetValues("some-header").First(), Is.Not.Empty, "");
4

3 回答 3

29

您可以使用虚拟/假处理程序 ( ) 设置InnerHandler您正在测试的 DelegatingHandler ( ) 的属性,如评论中链接的帖子中所示 。FooHandlerTestHandler

public class TestHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return Task.Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.OK), cancellationToken);
    }
}

 // in your test class method
    var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://example.com/");
    var handler = new FooHandler()
    {
        InnerHandler = new TestHandler()  // <-- change to use this

    };

    var invoker = new HttpMessageInvoker(handler);
    var result = await invoker.SendAsync(httpRequestMessage, new CancellationToken());

    Assert.That(result.Headers.GetValues("some-header").First(), Is.Not.Empty, "");

与那篇文章不同,这应该是您运行测试所需的最低设置。

于 2016-05-13T20:53:57.367 回答
2

使用using Moq.Protected;,您可以更好地控制响应结果。

var request = new HttpRequestMessage();

var innerHandlerMock = new Mock<DelegatingHandler>(MockBehavior.Strict);
innerHandlerMock
  .Protected()
  .Setup<Task<HttpResponseMessage>>("SendAsync", request, ItExpr.IsAny<CancellationToken>())
  .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK));

var handler = new FooHandler()
{
  InnerHandler = innerHandlerMock.Object
};
var invoker = new HttpMessageInvoker(handler);

// act
await invoker.SendAsync(request, default);
于 2021-01-05T12:49:23.470 回答
1

使用例如System.Net.Http.HttpClientHandlerSystem.Web.Http.HttpServer作为 InnerHandler:

var handler = new FooHandler()
{
    InnerHandler = new System.Net.Http.HttpClientHandler()
};

或者

var handler = new FooHandler()
{
    InnerHandler = new System.Web.Http.HttpServer() 
};
于 2017-09-14T09:39:13.780 回答