【问题标题】:How can I unit test delegating handler如何对委托处理程序进行单元测试
【发布时间】: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


    【解决方案1】:

    答案很简单,你不应该。你应该做的是:

    1. 对单元进行单元测试。那是一段简单的代码,旨在做一件或几件事情。
    2. 为每个处理程序单独创建测试。
    3. 为配置期间发生的处理程序构造创建测试。

    您不应该测试链如何作为单元测试工作,因为这会过度扩大范围并使单元测试无法维护。

    这就是集成测试的目的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-01
      • 2013-10-24
      • 2020-06-02
      • 2016-07-29
      • 1970-01-01
      相关资源
      最近更新 更多