2009-09-21 46 views
2

我有下面的覆蓋使用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 
    } 

回答

3

Controller.Initialize(RequestContext)調用內部ControllerBase.Execute(RequestContext),這反過來又可以通過明確的實施IController.Execute(RequestContext)被調用,所以這段代碼將初始化並執行控制器:

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

我已經分析了依賴關係樹對於Initialize(),我看不到任何其他方式調用這種方法,而不訴諸反思。您將需要創建RequestContext傳遞給Execute()爲好,這是比較容易,因爲它看起來像你使用起訂量:

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

This link對嘲諷的HttpContext的使用起訂量有幫助的細節。

+0

謝謝,山姆。我能夠觸發Initialize方法,但仍然出現錯誤,嘲笑httpContext比我想象的要困難得多。 – Geo 2009-09-22 01:24:58

+0

HttpContext是可測試性的反基督 - 我儘量遠離它,我很驚訝Initialize()也是如此弱測試。也許你可以看看使用自定義模型綁定器或屬性依賴注入,而不是使用Initialize()呢? – Sam 2009-09-22 01:38:04

相關問題