Lets take the following action method on our Home controller.
Unit testing this action method can be difficult due to its dependency on the Request object. Luckily the Request object here maps to the HttpContext of the controller. The HttpContext on the controller is an instance of HttpContextBase and can be mocked in unit tests.
Below is a class I currently use to mock out the HttpContext. Note that I have many other properties mocked that are part of the HttpContext. I plan on doing other blog posts using those different properties in the future.
In the constructor I new up the new mocks and do some wiring up of the dependencies of the objects you will need while working with the HttpContext. Since the above action uses a cookie, note that there is a Cookies property that is mapped to the mocked request object. So when Request.Cookies is called in the action method it will actually be looking at the Cookies collection defined in this class.
Here is a test that uses the MockContext object to test the action method above.
Note that I new up a new instance of the MockContext and add the cookie to the cookie collection so the action method above will have access to it. When creating an instance of the controller I used an object initializer to set the controller context to a new controller context using our MockContext http object.
Using this technique it would be very easy to mock out what would happen if the cookie was not in the cookies collection.