MoQ如何设置同一方法的多个调用

时间:2012-06-24 05:15:05

标签: vb.net 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中的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;
    }

2 个答案:

答案 0 :(得分: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; })

答案 1 :(得分:0)

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

为了澄清,要测试3次登录失败的情况,你不要拨打LoginBo 3次;你用一个已经准备好失败的设置来调用它一次。