我有問題設置模擬失敗,如果用戶嘗試登錄三次失敗。我的代碼如下所示:MoQ如何設置多個調用相同的方法
<TestMethod()>
Public Sub User_LogIn_With_Three_Failed_Attempts_AccountLocks_Pass()
' arrange
Dim logInMock As New Moq.Mock(Of IUserLoginRepository)()
logInMock.Setup(Function(repo) repo.LogInUser(It.IsAny(Of String), It.IsAny(Of String))).Returns(False)
' Todo: have to instruct the mock that if it is repeated 3 times then lock the account. How to do this????
' act
Dim logInBO As New LogInBO(logInMock.Object)
logInBO.LogIn("someusername", "someWrongPassword")
logInBO.LogIn("someusername", "someWrongPassword")
logInBO.LogIn("someusername", "someWrongPassword")
' verify
logInMock.Verify(Function(r) r.LogInUser("someusername", "someWrongPassword"), times:=Times.Exactly(3))
logInMock.Verify(Function(r) r.IsAccountLocked = True)
End Sub
假設我的倉庫看起來像:
public interface IUserLoginRepository
{
bool LogInUser(string userName, string password);
bool IsAccountLocked { get; }
bool ResetPassword(string userName, string password);
int FailedAttempts(string userName);
bool LockAccount(string userName);
}
欣賞任何提示,他會喜歡在VB.Net ;-)
的LoginBo代碼的起訂量語法是這樣的:
public bool LogIn(string userName, string password)
{
if (_logInRepo.IsAccountLocked)
// TODO log error
return false;
if (_logInRepo.LogInUser(userName, password))
{
return true;
}
else
{
if (_logInRepo.FailedAttempts(userName) == 3) // this should increment the failed attempts and return the value
_logInRepo.LockAccount(userName);
}
// Log error
return false;
}
嗨eyossi,謝謝你的帖子。這似乎並不正確。 logInBo.Setup? loginBo是我的課程,我不想嘲笑它。我想要的是,如果用戶嘗試3次登錄並失敗,則調用Repository LockAccount。我應該能夠驗證LockAccount被調用並且AccountIsLocked爲真。你可以請更新你的代碼,澄清事情?我只是想在我的上面的測試函數中填充「TODO」thingo的一些代碼。 – user1477660
誰調用LockAccount方法? logInBO?誰更改了「IsAccountLocked」值? (我想這裏是實現IUserLoginRepository本身的對象) – eyossi
好吧,它是LogInBo獲取LogInRepository作爲我試圖模擬的構建依賴項。 ... LoginBo中的代碼如下所示: – user1477660