代码之家  ›  专栏  ›  技术社区  ›  Geo

如何在尝试单元测试时触发初始化方法?

  •  2
  • Geo  · 技术社区  · 16 年前

    我有下面的覆盖,可以使用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
        }
    
    1 回复  |  直到 16 年前
        1
  •  3
  •   Sam    16 年前

    Controller.Initialize(RequestContext) 在内部调用 ControllerBase.Execute(RequestContext) ,然后可以通过 IController.Execute(RequestContext) ,因此此代码将初始化并执行控制器:

    IController controller = new TestController();
    controller.Execute(requestContext);

    我分析了依赖树 Initialize() 如果不借助反射,我就看不到任何其他调用此方法的方法。您需要创建 RequestContext 传递给 Execute() 此外,这看起来更容易,因为您使用的是MOQ:

    var wrapper = new HttpContextWrapper(httpContext);
    var requestContext = new RequestContext(wrapper, new RouteData());
    

    This link 有关于使用moq模拟httpContext的有用细节。