2011-10-04 79 views
0

我需要为我的应用程序创建单元测试策略。在我的ASP.NET MVC应用程序中,我将使用会话,现在我需要知道如何对使用会话的Action进行单元测试。我需要知道是否有涉及Sessions的单元测试操作方法框架。单元测试ASP.NET MVC应用程序 - 会话变量

回答

2

如果你需要模拟会话,你做错了 :) MVC模式的一部分是操作方法不应该有任何其他依赖关系比参数。因此,如果您需要会话,请尝试“包装”该对象并使用模型绑定(您的自定义模型绑定器,不是从POST数据绑定,而是从会话绑定)。

事情是这样的:

public class ProfileModelBinder : IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     if (bindingContext.Model != null) 
      throw new InvalidOperationException("Cannot update instances"); 

     Profile p = (Profile)controllerContext.HttpContext.Session[BaseController.profileSessionKey]; 
     if (p == null) 
     { 
      p = new Profile(); 
      controllerContext.HttpContext.Session[BaseController.profileSessionKey] = p; 
     } 
     return p; 
    } 
} 

不要忘记注册它,而应用程序启动了,比你可以使用这样的:

public ActionResult MyAction(Profile currentProfile) 
{ 
    // do whatever.. 
} 

不错,完全可测试的,享受:)