Asp.net-Mvc

如何對使用 FormsAuthentication 的 ASP.NET MVC 控制器進行單元測試?

  • December 14, 2008

我正在以測試驅動的方式使用 ASP.NET MVC 解決方案,並且我想使用表單身份驗證將使用者登錄到我的應用程序。我想在控制器中結束的程式碼如下所示:

FormsAuthentication.SetAuthCookie(userName, false);

我的問題是如何編寫測試來證明此程式碼的合理性?

有沒有辦法檢查是否使用正確的參數呼叫了 SetAuthCookie 方法?

有沒有辦法注入一個假的/模擬的 FormsAuthentication?

我將首先編寫一個介面和一個封裝此邏輯的包裝類,然後在我的控制器中使用該介面:

public interface IAuth 
{
   void DoAuth(string userName, bool remember);
}

public class FormsAuthWrapper : IAuth 
{
   public void DoAuth(string userName, bool remember) 
   {
       FormsAuthentication.SetAuthCookie(userName, remember);
   }
}

public class MyController : Controller 
{
   private readonly IAuth _auth;

   public MyController(IAuth auth) 
   {
       _auth = auth;
   }

}

現在IAuth可以在單元測試中輕鬆地模擬並驗證控制器是否呼叫了預期的方法。我不會對這個FormsAuthWrapper類進行單元測試,因為它只是將呼叫委託給FormsAuthentication它應該做的事情(微軟保證:-))。

引用自:https://stackoverflow.com/questions/366388