模拟 HttpContext (会话)

本文关键字:会话 HttpContext 模拟 | 更新日期: 2023-09-27 18:17:25


我读过很多关于在 mvc 中嘲笑的文章和博客......他们中的许多人很有帮助,但我仍然有一些问题:

    一个
  • 这样的问题是我需要在我的操作结果中使用会话,但是在我的测试中,当访问会话时,我得到一个 NullReferenceException。

    public ActionResult Index()
    {
      if (Session["Something"] == null)
      {
        Session.Add("Something", <smth>);
      }
      else
      {
        Session["Something"] = <smth>;
      }
      return redirect to action("Index2");
    }
    
  • 我的测试如下所示:

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

模拟 HttpContext (会话)

您可以使用 MVC-contrib TestHelper 等工具

来自网站的此示例演示如何测试在会话中存储已发布表单值的操作

[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"]);
}