模拟 HttpContext(会话)

发布于 2024-12-20 12:16:26 字数 545 浏览 2 评论 0原文


我读过很多关于 mvc 中模拟的文章和博客...其中许多很有帮助,但我仍然遇到一些问题:

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

    公共 ActionResult Index()
    {
      if (会话["某事"] == null)
      {
        Session.Add("某事", );
      }
      别的
      {
        会话["某事"] = ;
      }
      返回重定向到操作(“Index2”);
    }
    
  • 我的测试如下所示:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戏剧牡丹亭 2024-12-27 12:16:26

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

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"]);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文