在 MVC 3 中模拟会话

发布于 2024-10-20 04:19:49 字数 850 浏览 2 评论 0原文

我正在尝试使用 Moq 模拟控制器的会话变量。我一直遇到的问题是,会话在测试中是可见的,但在实际控制器中为空。

测试代码:

[TestMethod]
public void SessionTest()
{
    var controller = new BaseController();
    var controllerContext = new Mock<ControllerContext>();
    controllerContext.Setup(cc => cc.HttpContext.Session["user"]).Returns(new User());
    controller.ControllerContext = controllerContext.Object;

    User currentUser = controller.CurrentUser; //fails (throws NullReferenceException)
    User currentUser = (User)controller.Session["test"]; //works
}

控制器代码:

public User CurrentUser
{
    get
    {
        return (User)Session["user"]; //HttpContext is null at this point
    }
}

上面的代码遵循我见过的最常见的模式(几个 SO 帖子、Action Ch. 7 示例中的 MVC 2 等),但仍然不起作用。在控制器内部,ControllerContext 为 null,HttpContext 也为 null。我做错了什么?

I am attempting to mock a controller's Session variable using Moq. What I keep running into is that the Session is visible from the test, but null inside the actual controller.

Test code:

[TestMethod]
public void SessionTest()
{
    var controller = new BaseController();
    var controllerContext = new Mock<ControllerContext>();
    controllerContext.Setup(cc => cc.HttpContext.Session["user"]).Returns(new User());
    controller.ControllerContext = controllerContext.Object;

    User currentUser = controller.CurrentUser; //fails (throws NullReferenceException)
    User currentUser = (User)controller.Session["test"]; //works
}

Controller code:

public User CurrentUser
{
    get
    {
        return (User)Session["user"]; //HttpContext is null at this point
    }
}

The code above follows the most common pattern I've seen (several SO postings, the MVC 2 in Action Ch. 7 example, etc.), but still doesn't work. Inside the controller, the ControllerContext is null, as is the HttpContext. What am I doing wrong?

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

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

发布评论

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

评论(1

美胚控场 2024-10-27 04:19:49

这肯定是由于将单元测试项目添加到现有项目而引起的配置问题,因为我刚刚创建了一个新的 MVC 3 项目,选中了“创建单元测试项目”,添加了所有控制器、模型等。从旧项目到新项目,一切都很好。

It must have been a configuration issue caused by adding a unit test project to an already-existing project, because I just created a new MVC 3 project, checked the 'Create Unit Test Project', added all of my controllers, models, etc. from the old project to the new one, and it's working just fine.

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