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

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s