Writing unit tests for DelegatingHandler's

Topics: Web Api
Jan 20, 2012 at 7:58 PM

This seems impossible in the current release as you cannot invoke the SendAsync method as its protection level is set to protected internal. Is this intended?

Currently I have to resort to reflector trickery or implement my DelegatingHandler's using following pattern::

public class MyHandler : DelegatingHandler
        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
            return this.PublicSendAsync(request, cancellationToken);

        public Task<HttpResponseMessage> PublicSendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
return base.SendAsync(request, cancellationToken); }
I would replace the content of the PublicSendAsync with my custom logic. In my unit tests I can now call the PublicSendAsync method.

Jan 20, 2012 at 8:09 PM

Instead of unit testing the handler, why don't you offload the actual work into another class and invoke that class from the handler.

Then you can just test that class, and assume the delegating handler works when a functional test succeeds.

Jan 20, 2012 at 8:12 PM
Edited Jan 20, 2012 at 8:12 PM

Or you can make a class in your test that inherits from MyHandler, and then you can invoke it from inside there. Instead of mucking your code, muck the test.


Jan 20, 2012 at 8:21 PM

Alternative is you can just use HttpClient. Instantiate an HttpClient passing in the handler you want to test in the ctor. Then just invoke the client methods and they delegate to the handler.

Feb 9, 2012 at 4:46 AM

Hi Glenn,

WebAPI Preview 5

I m getting following error while unit testing delegatingHandler as mentioned above by you.

In a unit test when it successfully process logic in the Delegating Handler and throws exception at  "return base.SendAsync(request, cancellationToken);"

System.InvalidOperationException : The inner handler has not been assigned.


"return base.SendAsync(request, cancellationToken);" works fine for the normal course of the application flow. It just the unit tests.


Do we need set up the WebAPiConfiguration/HttpConfiguration so it does not through exception ???

Mar 19, 2012 at 10:28 AM

Assuming you've upgraded to MVC 4 Beta 2 - check out:


Mar 22, 2012 at 12:12 AM

Thank you, nope we haven't upgraded yet, but will be sooner.