如何在ASP.NET MVC 4 Web API中测试自定义DelegatingHandler
本文关键字:API 测试 自定义 DelegatingHandler Web ASP NET MVC | 更新日期: 2023-09-27 18:28:28
我在一些地方看到过这个问题,但没有看到任何好的答案。由于我不得不自己做过几次,我想我应该发布我的解决方案。如果你有更好的东西,请发帖。
注意:这是使用Web API的ASP.NET MVC 4 Beta 2版本-未来版本可能会更改!
更新:这在ASP.NET MVC 4 RC 中仍然有效
在这种方法中,我创建了一个TestHandler,并将其设置为测试中处理程序的InnerHandler
属性。
然后,可以将测试中的处理程序传递给HttpClient
——如果您正在编写服务器端处理程序,这可能看起来不直观,但这实际上是一种测试处理程序的轻量级方法——它将以与服务器中相同的方式调用。
默认情况下,TestHandler只会返回一个HTTP200,但它的构造函数接受一个函数,您可以使用该函数对传递的请求消息进行断言从测试中的处理程序传入。最后,您可以对来自客户端的SendAsync调用的结果进行断言。
设置好所有内容后,在客户端实例上调用SendAsync
来调用处理程序。请求将被传递到处理程序中,它将把它传递给TestHandler(假设它传递了调用),然后TestHandler将向处理程序返回响应。
测试处理程序如下所示:
public class TestHandler : DelegatingHandler
{
private readonly Func<HttpRequestMessage,
CancellationToken, Task<HttpResponseMessage>> _handlerFunc;
public TestHandler()
{
_handlerFunc = (r, c) => Return200();
}
public TestHandler(Func<HttpRequestMessage,
CancellationToken, Task<HttpResponseMessage>> handlerFunc)
{
_handlerFunc = handlerFunc;
}
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
return _handlerFunc(request, cancellationToken);
}
public static Task<HttpResponseMessage> Return200()
{
return Task.Factory.StartNew(
() => new HttpResponseMessage(HttpStatusCode.OK));
}
}
在测试中使用想象中的MyHandler
的示例。对断言使用NUnit。:
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://test.com");
httpRequestMessage.Headers.Add("username", "test");
var handler = new MyHandler()
{
InnerHandler = new TestHandler((r,c) =>
{
Assert.That(r.Headers.Contains("username"));
return TestHandler.Return200();
})
};
var client = new HttpClient(handler);
var result = client.SendAsync(httpRequestMessage).Result;
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.OK));
对于许多测试来说,TestHandler的默认行为可能很好,并使代码更简单。测试中处理程序的设置如下所示:
var handler = new MyHandler();
handler.InnerHandler = new TestHandler();
我喜欢这种方法,因为它在测试方法中保留了所有断言,并且TestHandler
非常可重用。
我只是在寻找同样的东西,但想出了一个不使用http客户端的更简洁的方法。我想要一个测试来断言消息处理程序使用了一个模拟的日志记录组件。我并不真的需要内部处理程序来运行,只是为了"存根"它以满足单元测试。适用于我的目的:)
//ARRANGE
var logger = new Mock<ILogger>();
var handler= new ServiceLoggingHandler(logger.Object);
var request = ControllerContext.CreateHttpRequest(Guid.NewGuid(), "http://test",HttpMethod.Get);
handler.InnerHandler = new Mock<HttpMessageHandler>(MockBehavior.Loose).Object;
request.Content = new ObjectContent<CompanyRequest>(Company.CreateCompanyDTO(), new JsonMediaTypeFormatter());
var invoker = new HttpMessageInvoker(handler);
//ACT
var result = invoker.SendAsync(request, new System.Threading.CancellationToken()).Result;
//ASSERT
<Your assertion>
我也找到了这个答案,因为我有我的自定义处理程序,我想测试它我们正在使用NUnit和Moq,所以我认为我的解决方案对有帮助
using Moq;
using Moq.Protected;
using NUnit.Framework;
namespace Unit.Tests
{
[TestFixture]
public sealed class Tests1
{
private HttpClient _client;
private HttpRequestMessage _httpRequest;
private Mock<DelegatingHandler> _testHandler;
private MyCustomHandler _subject;//MyCustomHandler inherits DelegatingHandler
[SetUp]
public void Setup()
{
_httpRequest = new HttpRequestMessage(HttpMethod.Get, "/someurl");
_testHandler = new Mock<DelegatingHandler>();
_subject = new MyCustomHandler // create subject
{
InnerHandler = _testHandler.Object //initialize InnerHandler with our mock
};
_client = new HttpClient(_subject)
{
BaseAddress = new Uri("http://localhost")
};
}
[Test]
public async Task Given_1()
{
var mockedResult = new HttpResponseMessage(HttpStatusCode.Accepted);
void AssertThatRequestCorrect(HttpRequestMessage request, CancellationToken token)
{
Assert.That(request, Is.SameAs(_httpRequest));
//... Other asserts
}
// setup protected SendAsync
// our MyCustomHandler will call SendAsync internally, and we want to check this call
_testHandler
.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", _httpRequest, ItExpr.IsAny<CancellationToken>())
.Callback(
(Action<HttpRequestMessage, CancellationToken>)AssertThatRequestCorrect)
.ReturnsAsync(mockedResult);
//Act
var actualResponse = await _client.SendAsync(_httpRequest);
//check that internal call to SendAsync was only Once and with proper request object
_testHandler
.Protected()
.Verify("SendAsync", Times.Once(), _httpRequest, ItExpr.IsAny<CancellationToken>());
// if our custom handler modifies somehow our response we can check it here
Assert.That(actualResponse.IsSuccessStatusCode, Is.True);
Assert.That(actualResponse, Is.EqualTo(mockedResult));
//...Other asserts
}
}
}
我创建了以下内容来测试DelegatingHandlers。对于使用HttpRequestMessage.DependencyScope的处理程序来说,使用您喜欢的IoC框架来解析依赖关系是很有用的,例如带有WindsorContainer:的WindsorDependencyResolver
public class UnitTestHttpMessageInvoker : HttpMessageInvoker
{
private readonly HttpConfiguration configuration;
public UnitTestHttpMessageInvoker(HttpMessageHandler handler, IDependencyResolver resolver)
: base(handler, true)
{
this.configuration = new HttpConfiguration();
configuration.DependencyResolver = resolver;
}
[DebuggerNonUserCode]
public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
request.Properties["MS_HttpConfiguration"] = this.configuration;
return base.SendAsync(request, cancellationToken);
}
}
另一种选择可能是存根
public class TestingHandlerStub : DelegatingHandler
{
private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _handlerFunc;
public TestingHandlerStub(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handlerFunc)
{
_handlerFunc = handlerFunc;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return _handlerFunc(request, cancellationToken);
}
}
这就是如何结合:
var handler = new YourCustomHandler()
{
InnerHandler = new TestingHandlerStub((r, c) =>
{
return Task.FromResult(httpResponseMessage);
})
};
var client = new HttpClient(handler);