2012-07-09 85 views
7

嗨,我正在做我的ASP.Net MVC2項目的單元測試。我正在使用Moq框架。在我LogOnController,FormsAuthentication.SetAuthCookie使用Moq嘲弄

[HttpPost] 
public ActionResult LogOn(LogOnModel model, string returnUrl = "") 
{ 
    FormsAuthenticationService FormsService = new FormsAuthenticationService(); 
    FormsService.SignIn(model.UserName, model.RememberMe); 

} 

在FormAuthenticationService類,

public class FormsAuthenticationService : IFormsAuthenticationService 
    { 
     public virtual void SignIn(string userName, bool createPersistentCookie) 
     { 
      if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot  be null or empty.", "userName"); 
      FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); 
     } 
     public void SignOut() 
     { 
      FormsAuthentication.SignOut(); 
     } 
    } 

我的問題是如何避免執行

FormsService.SignIn(model.UserName, model.RememberMe); 

此行。或者是有什麼辦法使用起訂量框架沒有改變我的ASP.Net MVC2項目,起訂量

FormsService.SignIn(model.UserName, model.RememberMe); 

+0

什麼是SUT(被測系統) - LogOnController或FormsAuthenticationService?如果它是前者,則應該爲'FormsAuthenticationService'提供一個僞造品,並且應該驗證是否調用了SignIn'方法。後者很難單元測試,因爲它需要一個當前的'HttpContext'來添加一個cookie(到'HttpResponse')。 – 2012-07-09 13:37:02

+0

我想測試LogOnController。我試圖模擬FormsService.SignIn(model.UserName,model.RememberMe); 以這種方式, var formService = new Mock (); 但formservice.SignIn不返回任何內容。我該如何避免執行該行或如何嘲笑該行。我不知道如何使用Moq來模擬。 – Dilma 2012-07-10 04:43:43

回答

9

進樣IFormsAuthenticationService作爲依賴於你的LogOnController這樣

private IFormsAuthenticationService formsAuthenticationService; 
public LogOnController() : this(new FormsAuthenticationService()) 
{ 
} 

public LogOnController(IFormsAuthenticationService formsAuthenticationService) : this(new FormsAuthenticationService()) 
{ 
    this.formsAuthenticationService = formsAuthenticationService; 
} 

第一個構造是,這樣的IFormsAuthenticationService正確的實例在運行時使用的框架。

在您的測試

現在,通過將模擬如下

var mockformsAuthenticationService = new Mock<IFormsAuthenticationService>(); 
//Setup your mock here 

更改您的操作代碼使用私有字段formsAuthenticationService如下

[HttpPost] 
public ActionResult LogOn(LogOnModel model, string returnUrl = "") 
{ 
    formsAuthenticationService.SignIn(model.UserName, model.RememberMe); 
} 

希望這會創建使用其他構造函數的LogonController實例幫助。我已經爲你省去了模擬設置。如果你不確定如何設置,請告訴我。

+0

謝謝Suhas。我不知道該把代碼放在哪裏,因爲我是ASP.Net的新手u =單元測試。你的意思是我應該改變我的LogOnController在mvc項目中?請善待解釋。提前致謝。 – Dilma 2012-07-10 04:53:52

+0

謝謝..它的工作..謝謝你Suhas。 – Dilma 2012-07-10 06:12:58

+0

我希望你現在很清楚。讓我知道你是否仍然面臨這個問題。 – Suhas 2012-07-10 08:05:53