C# 如何在尝试单元测试时触发初始化方法?
我有下面的覆盖,可以使用FormSideEntity对象对Cookie执行一些操作。但是,当我在单元测试中实例化控制器时,不会触发此方法。有什么办法吗C# 如何在尝试单元测试时触发初始化方法?,c#,asp.net-mvc,unit-testing,moq,C#,Asp.net Mvc,Unit Testing,Moq,我有下面的覆盖,可以使用FormSideEntity对象对Cookie执行一些操作。但是,当我在单元测试中实例化控制器时,不会触发此方法。有什么办法吗 protected override void Initialize(System.Web.Routing.RequestContext requestContext) { base.Initialize(requestContext); // Grab the user's login infor
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
}
Controller.Initialize(RequestContext)
在ControllerBase.Execute(RequestContext)
内部调用,而IController.Execute(RequestContext)
的显式实现又可以调用它,因此此代码将初始化并执行控制器:
IController controller = new TestController();
controller.Execute(requestContext);
我已经分析了Initialize()
的依赖关系树,我看不到任何其他不借助反射调用此方法的方法。您还需要创建传递给Execute()
的RequestContext
,这看起来更容易,因为您正在使用Moq:
var wrapper = new HttpContextWrapper(httpContext);
var requestContext = new RequestContext(wrapper, new RouteData());
有关于使用Moq模拟HttpContext的有用详细信息。谢谢,Sam。我能够触发Initialize方法,但仍然会出错,模拟HttpContext比我想象的要困难得多。HttpContext是可测试性的反基督-我尽量远离它,我很惊讶Initialize()也是很弱的可测试性。也许您可以考虑使用自定义模型绑定器或属性依赖项注入,而不是使用Initialize()?