TheBoubou
TheBoubou

Reputation: 19903

ASP.NET MVC HttpContext in test method

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 ?

Thanks,

Upvotes: 0

Views: 1111

Answers (3)

Tomasz Jaskuλa
Tomasz Jaskuλa

Reputation: 16013

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.

Upvotes: 0

Timbo
Timbo

Reputation: 4533

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.

Upvotes: 0

Related Questions