Rohit
Rohit

Reputation: 10286

How can I unit test delegating handler

I have an httpClient which has timeout,retry,authorization delegating handlers.

        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);

I am following along a tutorial and I am trying to unit test my timeout handler

    [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();
    }

I am stuck at this point. How can i chain those handlers in unit test project?

Upvotes: 1

Views: 1276

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26450

The answer is very simple you should not. What you should do is:

  1. Unit test the units. That is a simple piece of code, design to do a single or few things.
  2. Create tests for each handler individually.
  3. Creat tests for the handler construction that occurs during configuration.

You should not test how the chains work as unit tests, as this broadens the scope too much and renders the unit tests unmaintainable.

That's what integration testing is for.

Upvotes: 2

Related Questions