在 MVC 3 中模拟会话
我正在尝试使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这肯定是由于将单元测试项目添加到现有项目而引起的配置问题,因为我刚刚创建了一个新的 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.