嘲讽的HttpContext(会话) [英] Mocking HttpContext (Session)

查看:115
本文介绍了嘲讽的HttpContext(会话)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


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


  • 其中一个问题是,我需要在我的ActionResult使用会话,但在我的测试中,我得到当会话访问一个NullReferenceException。

  • 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);
    


  • 推荐答案

    您可以使用工具,如的 MVC-的contrib TestHelper

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

    这篇关于嘲讽的HttpContext(会话)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆