Sep 22nd 2008 08:05 pm
Testing HTTP Handlers And Modules Without A Web Server
Recently I came across this posting at Cozi Tech Blog:
A Way To Unit Test ASP.NET IHttpHandler Implementations
If you find yourself writing simple HTTP handler code that produces and consumes structured data (for instance, some RESTful application), you may wonder how to test it without fiddling with IIS or configuration files. Here’s a trick to write pure unit tests that verify your
IHttpHandlerimplementation does what you expect. By “pure unit tests”, I mean test code that:
- works without configuration files (like web.config);
- needs no servers (like Cassini, IIS, or your own mock HTTP server with full ASP.NET pipeline that you were about to write and debug just before you stumbled upon this article);
- doesn’t access file system (like ashx files);
avoids globals (like HttpContext.Current).
…
At the core of the post is the System.Web.Hosting.SimpleWorkerRequest object in the System.Web.Hosting namespace. It provides an easy way to create http requests and pass them to a handler. The posting gives a nice example and referencing a custom version of SimpleWorkerRequest on google code.
The SimpleWorkerRequest implementation referenced has a small bug with querystring values and is limited in scope. Some additional things I wanted to test were HTTP Headers (expiration, mime type, etc.) and file attachments. To test these things, modify WorkerRequestStub to override SendResponseFile, SendKnownResponseHeaders, and SendUnknownResponseHeaders to track and expose the headers and file submissions to the testing container.
While testing web based UIs is still a difficult and expensive problem there’s no reason testing web services should be.
No Comments yet »