0

如果用户尝试登录三次失败,我将无法设置模拟失败。我的代码如下所示:

<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 中的 moq 语法;-)

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;
    }
4

2 回答 2

1

好的,现在我得到了你想要做的事情。所以忽略我在编辑之前写的内容。

Dim logInMock As New Moq.Mock(Of IUserLoginRepository)()

Dim IsAccountLocked = false

logInMock.SetupGet(Function(repo) repo.IsAccountLocked).Returns(Function() { return isAccountLocked })


dim amountOfFailedlogIns = 0;
logInMock.Setup(Function(repo) repo.LogInUser(It.IsAny(Of String), It.IsAny(Of String))).Callback(Function(repo) amountOfFailedlogIns++).Returns(False)

logInMock.Setup(Function(repo) repo.FailedAttempts(It.IsAny(Of String))).Returns(Function(repo) return amountOfFailedlogIns)

在 C# 中:

Mock<IUserLogicRepository> logInMock = new Mock<IUserLoginRepository>();

bool IsAccountLocked = false

logInMock.SetupGet(repo => repo.IsAccountLocked).Returns(() => { return isAccountLocked; })


int amountOfFailedlogIns = 0;
logInMock.Setup(repo => repo.LogInUser(It.IsAny<string>(), It.IsAny<string>()))).Callback(repo => { amountOfFailedlogIns++; }).Returns(false);

logInMock.Setup(repo => repo.FailedAttempts(It.IsAny<string>()).Returns(repo => { return amountOfFailedlogIns; })
于 2012-06-24T05:49:35.700 回答
0

在我看来,这LoginRepo就是你想要嘲笑的。您设置了您的模拟存储库,以便它返回一个已经两次登录失败的用户,然后使用错误的凭据调用 LoginBo,然后验证该帐户已被锁定在模拟存储库中。

澄清一下,测试3次登录失败的情况,不要调用LoginBo 3次;您使用已经准备好失败的设置调用它一次。

于 2012-06-24T21:27:18.540 回答