Mock HttpRequest

Possibly save 2 hours of your time:

We often want to unit test our controller layer with the input request URL. Here is an example of unit test that can mock the HttpRequest within the HttpContext constructor that you can set on your controller.

private HttpContextBase MockCurrentContext()
{
var sb = new StringBuilder();
TextWriter w = new StringWriter(sb);
var context = new HttpContext(new HttpRequest(“”, “http://www.example.com “, “”), new HttpResponse(w));
return new HttpContextWrapper(context);
}

[OneTimeSetUp]
public void OneTimeSetUp()
{
controller = new YourController();
controller.ControllerContext = new ControllerContext(MockCurrentContext(), new RouteData(), controller);
}

Advertisements