Take the 2-minute tour ×

I have this in my controller

public ActionResult Testing()
    CustomerContactModel model = new CustomerContactModel();
    HttpContext.Current.Session["xxxx"] = "Data";

    return PartialView("MyPartialView", model);

I get an exception on HttpContext when I get run the controller action from my trest method. How can I solve this problem ?


share|improve this question
add comment

3 Answers

You have to mock HttpContext in your unit tests. Here's how you can do it with Moq framework : How do I mock the HttpContext in ASP.NET MVC using MOQ?

But you can also use MvcContrib TestControllerBuilder to do it easily. You have some examples here : http://mvccontrib.codeplex.com/wikipage?title=TestHelper&referringTitle=Documentation

An advice for the future, will be also to avoid as possible to depend on HttpContext in your controllers actions.

share|improve this answer
add comment

You can moq virtually anything, including the HttpContext, for testing methods:

Try this post as a starter.

Personally I try to make my ActionResult methods not needing testing, by keeping all the important code in the controllers and beyond...but if you do want to test them then mocking can be very handy.

share|improve this answer
add comment

Your Answer


