2014-04-23 109 views
1

,我們可以在asp.net mvc的編寫以下登錄控制器什麼樣的測試用例的MVC登錄NUnit測試案例

[HttpPost] 
[AllowAnonymous] 
[ValidateAntiForgeryToken] 
public ActionResult Login(LoginModel model, string returnUrl) 
{ 
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.PasswordpersistCookie: model.RememberMe)) 
{ 
    return RedirectToLocal(returnUrl); 
} 
ModelState.AddModelError("", "The user name or password provided is incorrect."); 
return View(model); 
} 

回答

5

1)您可以驗證WebSecurity.Login調用與正確的參數模型時有效

2)當WebSecurity.Login返回true您重定向到reutnrUrl

3)如果模式是無效的,你可以驗證ModelState中包含你的錯誤,且返回的ViewResult您可以驗證。

雖然您必須重構對WebSecurity的調用,但您必須嘲笑它​​。可能將不得不使用依賴注入技術。

1)你將不得不隱藏自己的WebSecurity接口後,只有通過該接口使用它(我假設你WebSecurity靜態類來自WebMatrix.WebData命名空間)。

public interface IWebSecurityHelper 
{ 
    bool Login(string userName, string password, bool isPersistent = false) 
} 

// Implementation of your web security helper 

using WebMatrix.WebData; 

public class WebSecurityHelper : IWebSecurityHelper 
{ 
    public bool Login(string userName, string password, bool isPersistent = false) 
    { 
     WebSecurity.Login(userName, password, isPersistent); 
    } 
} 

2)在你的控制器,你必須有創造WebSecurityHelper的一個實例,它通常是使用IoC框架做suchs StructureMapenter link description here。但是對於這個例子,我只是初始化控制器構造函數中的WebSecurityHelper,它仍然允許我注入模擬測試。

public class LoginController 
{ 
    private readonly IWebSecurityHelper _helper; 

    public LoginController(IWebSecurityHelper helper) 
    { 
    _helper = helper; 
    } 

    // passing your implementation of the WebSecurityHelper 
    public LoginController() : this(new WebSecurityHelper()) {} 

    [HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public ActionResult Login(LoginModel model, string returnUrl) 
    { 
     if (ModelState.IsValid && _helper.Login(model.UserName,model.PasswordpersistCookie: model.RememberMe)) 
     { 
     return RedirectToLocal(returnUrl); 
     } 

     ModelState.AddModelError("", "The user name or password provided is incorrect."); 

     return View(model); 
    }  
} 

3)在你的單元測試中,你將不得不模擬IWebSecurityHelper。有很多嘲諷框架,我個人比較喜歡Moq

[TestFixture] 
public class LoginControllerTests 
{ 
    // this test will verify that your controller called Login method of the WebSecurityHelper successfully with correct parameters 
    [Test] 
    public void LoginAction_Must_Call_WebSecurityLogin() 
    { 
     var loginModel = new LoginModel() { UserName = "test", Password = "test" } 

     var helperMock = new Mock<IWebSecurityHelper>(); 
     helperMock.Expect(m => m.Login(loginModel.UserName, loginModel.Password)); 
     var controller = new LoginController(_helperMock.Object); 
     controller.Login(loginModel, string.Empty); 
     helperMock.Verify(m => m.Login(loginModel.UserName, loginModel.Password)); 
    } 

} 
+0

我會在編輯後的答案中發佈一個簡單的例子。 – milagvoniduak

+0

看看這篇文章:http://stackoverflow.com/questions/12408349/membership-provider-must-be-an-instance-of-extendedmembershipprovider – milagvoniduak