1
我正在開發ASP.NET MVC 4上的應用程序。我正在使用TDD方法來開發我的應用程序。最初,我試圖爲應用程序實現登錄模塊。技術上爲了登錄,它需要遵循以下步驟:MVC Moq多重依賴項
- 驗證用戶帳戶沒有被鎖定,並且它是一個有效的用戶。 (如果用戶嘗試多次登錄,則必須在5次嘗試失敗後鎖定該帳戶。爲此,我的數據庫中有一個
LoginAttempt
字段,每次嘗試失敗後我都會更新) - 如果驗證帳戶,驗證用戶使用第三方服務的loginId和密碼。
- 如果通過驗證,用戶必須重定向到索引頁面。
爲了實現這些任務,我已經創建了:
// Interface, Controller will interact with
public Interface IAuthenticate
{
bool ValidateUser(string UserId,string Password);
}
// Class that implement IAuthenticate
public class Authenticate : IAuthenticate
{
private IVerifyUser loginVerify;
private IThirdPartyService thirdpartyService;
public Authenticate(IVerifyUser user,IThirdPartyService thirdparty)
{
this.loginVerify=user;
this.thirdpartyService=thirdparty;
}
public bool ValidateUser(string userId,string password)
{
if(loginVerify.Verify(userId))
{
if(thirdpartyService.Validate(userId,password))
return true;
else
return false;
}
else
return false;
}
}
爲了測試我的控制器登錄,我必須只創建IAuthenticate
一個模擬的還是我不得不爲IVerifyUser
和IThirdPartyService
創建模擬? ?
[TestMethod]
public void Login_Rerturn_Error_If_UserId_Is_Incorrect()
{
Mock<IAuthenticate> mock1 = new Mock<IAuthenticate>();
mock1.Setup(x => x.ValidateUser("UserIdTest", "PasswordTest"))
.Returns(false);
var results = controller.Login();
var redirect = results as RedirectToRouteResult;
Assert.IsNotNull(results);
Assert.IsInstanceOfType(results, typeof(RedirectToRouteResult));
controller.ViewData.ModelState.AssertErrorMessage("Provider", "User Id and Password is incorrect");
Assert.AreEqual("Index", redirect.RouteValues["action"], "Wrong action");
Assert.AreEqual("Home", redirect.RouteValues["controller"], "Wrong controller");
}
任何指導真的很感激??
你能否提供更多的細節?我怎麼做,任何指導方針將非常感激。 – Faisal
另外如果我必須測試IVerifyUser和IThirdPartyService? – Faisal