我有一个具有超时,重试,授权委托处理程序的httpClient。
var authorizationHandler = new AuthorizationDelegatingHandler();
var retryHandler = new RetryPolicyDelegatingHandler(3);
var timeoutHandler = new TimeOutDelegatingHandler(TimeSpan.FromSeconds(5));
authorizationHandler.InnerHandler = retryHandler;
retryHandler.InnerHandler = timeoutHandler;
_myHttpClient = new HttpClient(authorizationHandler);
我正在按照教程进行操作,并且尝试对超时处理程序进行单元测试
[TestMethod]
[ExpectedException(typeof(TimeoutException))]
public async Task GetDocuments_Timeout_MustThrowTimeoutException()
{
var unauthorizedResponseHttpMessageHandlerMock = new Mock<HttpMessageHandler>();
unauthorizedResponseHttpMessageHandlerMock.Protected().Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>()).ReturnsAsync(new HttpResponseMessage()
{
StatusCode = System.Net.HttpStatusCode.Unauthorized
});
var httpClient = new HttpClient(unauthorizedResponseHttpMessageHandlerMock.Object);
httpClient.BaseAddress = new Uri("http://localhost");
var timeoutHandler = new TimeOutDelegatingHandler(TimeSpan.FromSeconds(3));
var testableClass = new MyCustomclass(httpClient);
var cancellationSource = new CancellationTokenSource();
await testableClass.Foo();
}
我被困在这一点上。如何在单元测试项目中链接这些处理程序?
答案很简单,您不应该这样做。您应该做的是:
您不应测试链作为单元测试的工作方式,因为这会极大地扩大范围,并使单元测试无法维护。
这就是集成测试的目的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句