开发者

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("MyPartialV开发者_JAVA技巧iew", 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,


Try this:

http://haacked.com/archive/2007/06/19/unit-tests-web-code-without-a-web-server-using-httpsimulator.aspx


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜