如何在尝试单元测试时触发初始化方法?
我有下面的覆盖,可以使用 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
}
I have the override below to do a few things with cookies using the FormsIdentity Object. But when I instantiate a controller on my Unit Testing this method is not triggered. Any ideas how to do this?
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Controller.Initialize(RequestContext)
在ControllerBase.Execute(RequestContext)
内部调用,而后者又可以由IController.Execute(RequestContext) 的显式实现调用
,因此此代码将初始化并执行控制器:我已经分析了
Initialize()
的依赖关系树,并且我看不到在不诉诸反射的情况下调用此方法的任何其他方式。您还需要创建传递给Execute()
的RequestContext
,这更容易,因为看起来您正在使用 Moq:此链接提供了有关使用 Moq 模拟 HttpContext 的有用详细信息。
Controller.Initialize(RequestContext)
is invoked insideControllerBase.Execute(RequestContext)
, which in turn can be invoked by the explicit implementation ofIController.Execute(RequestContext)
, so this code will initialize and execute a controller:I've analyzed the dependency tree for
Initialize()
and I can't see any other way of invoking this method without resorting to Reflection. You will need to create theRequestContext
passed toExecute()
as well, which is easier as it looks like you are using Moq:This link has helpful details on mocking an HttpContext using Moq.