Mocking HttpContext

I have been working on a proof of concept of unit testing with Visual Studio Team System for one of my clients. They were already familiar with the term unit testing, but up to now they have only seen some presentations/demos about it but they are quite unsure how to use it in their projects, so they asked for a PoC in order to see how the unit testing would like with the particularities of their code.

 

As I started I couldn't see any "oddities" about their code, they had some database access layer components (which there are already tons of articles about how to test them), business components and so on....

 

But after testing a couple of components I found out that in some of their components they were using the HttpContext. So I decided to create a new object of such type and use it like a normal mock object filling their collections (forms, query string and session) with custom data. But I found out that it wasn't as easy as it seemed and even if you manage to create an HttpContext object you will find out that many other objects used inside it are read-only or internal so you can barely modify this object.

 

So, my first thought was to search in the web to see how other guy had run into the same problem and had created a class that creates a Mock HttpContext object. Unfortunately I found many forums with guys with my same problem, a couple of articles that solved partially the problem (they could only manipulate the cache collection) and other that used a non-free third party component.

 

Since I couldn't find out any already made component that did such I had to create one from scratch ... The only problems were to create objects that were declared as internals or overriding read-only collections. The solution was to use my favorite namespace (reflection). I also used the reflector tool to see the implementation of the HttpContext object to see how to "inject" my own collection in the place of the read-only collections.

 

I attached the code to create the Mock HttpContext, My purpose was not to lose a lot of time so don't expect to have a perfect class with all the properties/methods finished. At least, in my case, it solved all the problems. If you find out some problem that doesn't solve this component, or want some more explanations about how the component works, don't hesitate to contact me.

 

Enjoy.

 

MockHttpContext.zip