2016-03-22 47 views
1

我正在開發ASP.NET MVC 4上的應用程序。我正在使用TDD方法來開發我的應用程序。最初,我試圖爲應用程序實現登錄模塊。技術上爲了登錄,它需要遵循以下步驟:MVC Moq多重依賴項

  1. 驗證用戶帳戶沒有被鎖定,並且它是一個有效的用戶。 (如果用戶嘗試多次登錄,則必須在5次嘗試失敗後鎖定該帳戶。爲此,我的數據庫中有一個LoginAttempt字段,每次嘗試失敗後我都會更新)
  2. 如果驗證帳戶,驗證用戶使用第三方服務的loginId和密碼。
  3. 如果通過驗證,用戶必須重定向到索引頁面。

爲了實現這些任務,我已經創建了:

// 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一個模擬的還是我不得不爲IVerifyUserIThirdPartyService創建模擬? ?

[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"); 
} 

任何指導真的很感激??

回答

1

如果您正在測試您的控制器,並且您的控制器對IAuthenticate的實例有依賴性,那麼您就必須進行模擬。通過嘲笑它,你忽略了其中的任何實際實現。由於使用IAuthenticate發生的最終行爲,您只能測試控制器的行爲。

在單元測試中測試你的執行IAuthenticate,那麼你會嘲笑它的依賴(IVerifyUserIThirdPartyService),以測試它的行爲方式給無論從他們的方法有一定的最終結果。

如果您需要任何澄清,請評論! :)

+0

你能否提供更多的細節?我怎麼做,任何指導方針將非常感激。 – Faisal

+0

另外如果我必須測試IVerifyUser和IThirdPartyService? – Faisal