0
我需要爲我的應用程序創建單元測試策略。在我的ASP.NET MVC應用程序中,我將使用會話,現在我需要知道如何對使用會話的Action進行單元測試。我需要知道是否有涉及Sessions的單元測試操作方法框架。單元測試ASP.NET MVC應用程序 - 會話變量
我需要爲我的應用程序創建單元測試策略。在我的ASP.NET MVC應用程序中,我將使用會話,現在我需要知道如何對使用會話的Action進行單元測試。我需要知道是否有涉及Sessions的單元測試操作方法框架。單元測試ASP.NET MVC應用程序 - 會話變量
如果你需要模擬會話,你做錯了 :) 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..
}
不錯,完全可測試的,享受:)