我在下面使用FormsIdentity对象使用cookie做一些事情。但是当我在单元测试中实例化控制器时,不会触发此方法。任何想法如何做到这一点?
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
// Grab the user's login information from FormsAuth
_userState = new UserState();
if (this.User.Identity != null && this.User.Identity is FormsIdentity)
this._userState.FromString(((FormsIdentity)this.User.Identity).Ticket.UserData);
// have to explicitly add this so Master can see untyped value
this.UserState = _userState;
//this.ViewData["ErrorDisplay"] = this.ErrorDisplay;
// custom views should also add these as properties
}
答案 0 :(得分:3)
Controller.Initialize(RequestContext)
中调用了 ControllerBase.Execute(RequestContext)
,而IController.Execute(RequestContext)
的显式实现又可以调用它,因此这段代码将初始化并执行一个控制器:
IController controller = new TestController();
controller.Execute(requestContext);
我已经分析了Initialize()
的依赖关系树,如果不诉诸于Reflection,我看不到任何其他调用此方法的方法。您还需要创建传递给RequestContext
的{{1}},这样看起来更简单,因为您使用的是Moq:
Execute()
This link提供了有关使用Moq模拟HttpContext的有用详细信息。