Mocking HttpContext (Session)

痴心易碎 提交于 2019-12-13 19:39:36

问题



I've read many articles and blogs about mocking in mvc... Many of them were helpful, but i still have some problems:

  • One such issue is that I need to use Session in My ActionResult, but in my Tests i get a NullReferenceException when Session is accessed.

    public ActionResult Index()
    {
      if (Session["Something"] == null)
      {
        Session.Add("Something", <smth>);
      }
      else
      {
        Session["Something"] = <smth>;
      }
      return redirect to action("Index2");
    }
    
  • My test look like this:

    HomeController controller = new HomeController;
    var result = controller.Index() as ViewResult;
    Assert.AreEqual("Index2", result.ViewName);
    

回答1:


You can use tools such as the MVC-contrib TestHelper

This sample from the site shows how to test an action that stores a posted form value in the session

[Test]
public void AddSessionStarShouldSaveFormToSession()
{
    TestControllerBuilder builder = new TestControllerBuilder();
    StarsController controller = new StarsController();
    builder.InitializeController(controller);

    //note that this is assigned before the controller action. This simulates the server  filling out the form data from the request
    builder.Form["NewStarName"] = "alpha c";

    //this assumes that AddSessionStar takes the form data and adds it to the session
    controller.AddSessionStar();

    Assert.AreEqual("alpha c", controller.HttpContext.Session["NewStarName"]);
}


来源:https://stackoverflow.com/questions/8443746/mocking-httpcontext-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!