【发布时间】:2020-08-20 15:45:52
【问题描述】:
我有一个 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();
}
我被困在这一点上。如何在单元测试项目中链接这些处理程序?
【问题讨论】:
标签: c# unit-testing asp.net-web-api