ASP.NET Core by Ken

Testing DelegatingHandlers

DelegatingHandlers can be tested in isolation:

  1. Mock the Inner Handler:

    var mockHandler = new Mock<HttpMessageHandler>();
    mockHandler.Protected()
               .Setup<Task<HttpResponseMessage>>("SendAsync", ...)
               .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK));
  2. Inject into DelegatingHandler:

    var customHandler = new CustomHandler
    {
        InnerHandler = mockHandler.Object
    };
  3. Create HttpClient:

    var client = new HttpClient(customHandler);

This approach allows for unit testing the DelegatingHandler's logic without making actual HTTP calls.

UnitTesting
Mocking
DelegatingHandler
HttpClient
Testing

Comments