Search code examples
c#unit-testingasp.net-web-apidelegatinghandler

Unit testing DelegatingHandler


How do I unit test a custom DelegatingHandler? I have the following but its complaining the innerHandler not set.

var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://foo.com");
var handler = new FooHandler()
{
    InnerHandler = new FooHandler() 
};

var invoker = new HttpMessageInvoker(handler);
var result = await invoker.SendAsync(httpRequestMessage, new CancellationToken());

Assert.That(result.Headers.GetValues("some-header").First(), Is.Not.Empty, "");

Solution

  • You can set the InnerHandler property of the DelegatingHandler you're testing (FooHandler) with a dummy/fake handler (TestHandler) as shown in that linked post in your comment.

    public class TestHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
        }
    }
    
     // in your test class method
        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://example.com/");
        var handler = new FooHandler()
        {
            InnerHandler = new TestHandler()  // <-- change to use this
    
        };
    
        var invoker = new HttpMessageInvoker(handler);
        var result = await invoker.SendAsync(httpRequestMessage, new CancellationToken());
    
        Assert.That(result.Headers.GetValues("some-header").First(), Is.Not.Empty, "");
    

    Unlike that post, this should be the minimum you need to set up to get your test to run.