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(“”, “ “, “”), new HttpResponse(w));
return new HttpContextWrapper(context);

public void OneTimeSetUp()
controller = new YourController();
controller.ControllerContext = new ControllerContext(MockCurrentContext(), new RouteData(), controller);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s