Mocking the HttpContext in ASP.NET MVC

Thursday, 08 May 2008

Posted by Sébastien Lachance with Comments (0)

I just got a hard time figuring how I could be mocking the HttpContext so that I would be able to mock HttpRequest. But once you understand the principle, it is fairly easy.

First thing we need to know is that the HttpContext is held inside a ControllerContext object. Once we have instantiated one, we can then put it inside our controller.

controller.ControllerContext = new ControllerContext(mockedhttpContext, new RouteData(), controller);
 
Where mockedHttpContext is your mocked HttpContextBase object.
 
Inside the HttpContextBase object reside a lot of useful stuff that can replace with our mocks. By example, the HttpRequest, HttpServer, HttpApplication, etc, are all contained inside. So, getting familiar with this basic knowledge is a must to do testing usefully.
 
Next post : Mocking HttpRequest.Form to return what we want.



blog comments powered by Disqus