【问题标题】:Mocking HttpContext (Session)模拟 HttpContext (Session)
【发布时间】:2011-12-09 09:52:25
【问题描述】:


我已经阅读了很多关于在 mvc 中进行模拟的文章和博客......其中很多很有帮助,但我仍然有一些问题:

  • 一个这样的问题是我需要在我的 ActionResult 中使用 Session,但在我的测试中,当访问 Session 时我得到一个 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);
    

【问题讨论】:

    标签: c# asp.net-mvc unit-testing mocking httpcontext


    【解决方案1】:

    您可以使用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"]);
    }
    

    【讨论】:

    • 这只是使用会话值的手动测试...我需要测试所有的 ActionResult。而不是会话是一个测试点。我需要采用此操作提供的路线(操作\视图名称)...而且我只有一个 nullref 异常。我需要一种方法来提供一个未启动的操作来使用一个会话,这不是一个空对象
    • @AkmecNurik TestHelper 也会解决这个 NullReference 问题,TestControllerBuilder 会为你填写 Mock 实现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多