0

我正在尝试使用 Rhinomocks 3.5 和新的 lambda 表示法来模拟一些测试。我读过 这个,但还有很多问题。有没有完整的例子,特别是对于 MVC 类型的架构?

例如,模拟这个的最佳方法是什么。

    public void OnAuthenticateUnitAccount()
    {
        if(AuthenticateUnitAccount != null)
        {
            int accountID = int.Parse(_view.GetAccountID());
            int securityCode = int.Parse(_view.GetSecurityCode());
            AuthenticateUnitAccount(accountID, securityCode);
        }
    }

有一个视图界面和一个演示者界面。它在控制器上调用一个事件。

我想出的是这个。

[TestMethod()]
    public void OnAuthenticateUnitAccountTest()
    {
        IAuthenticationView view = MockRepository.GenerateStub<IAuthenticationView>();
        IAuthenticationPresenter target = MockRepository.GenerateMock<IAuthenticationPresenter>();

        target.Raise(x => x.AuthenticateUnitAccount += null, view.GetPlayerID(), view.GetSecurityCode());
        target.VerifyAllExpectations();
    }

它通过了,但我不知道它是否正确。

是的,我们正在开发后进行测试……需要快速完成。

4

1 回答 1

2

我假设这是在您的一个控制器中。此外,我假设您可以通过构造函数或设置器传递视图数据,并且您可以注册 AuthenticateUnitAccount 处理程序。鉴于此,我会执行以下操作:

[TestMethod]
public void OnAuthenticateUnitAccountSuccessTest()
{
    IAuthenticationView view = MockRepository.GenerateStub<IAuthenticationView>();
    view.Stub( v => GetPlayerID() ).Returns( 1 );
    view.Stub( v => GetSecurityCode() ).Returns( 2 );

    FakeAuthenticator authenticator = MockRepository.GenerateMock<FakeAuthenticator>();
    authenticator.Expect( a => a.Authenticate( 1, 2 ) );

    Controller controller = new Controller( view );
    controller.AuthenticateUnitAccount += authenticator.Authenticate;

    controller.OnAuthenicateAccount()

    authenticator.VerifyAllExpectations();
}

FakeAuthenticator 类包含一个与处理程序签名匹配的 Authenticate 方法。因为您需要知道是否调用了此方法,所以您需要模拟它而不是存根它以确保使用正确的参数等调用它。您会注意到我直接调用该方法而不是引发事件. 由于您只需要在这里测试您的代码,因此无需测试引发事件时会发生什么。您可能想在其他地方进行测试。在这里,我们只想知道使用正确的参数调用正确的方法。

对于失败,您可以执行以下操作:

[TestMethod]
[ExpectedException(typeof(UnauthorizedException))]
public void OnAuthenticateUnitAccountFailureTest()
{
    IAuthenticationView view = MockRepository.GenerateStub<IAuthenticationView>();
    view.Stub( v => GetPlayerID() ).Returns( 1 );
    view.Stub( v => GetSecurityCode() ).Returns( 2 );

    FakeAuthenticator authenticator = MockRepository.GenerateMock<FakeAuthenticator>();
    authenticator.Expect( a => a.Authenticate( 1, 2 ) )
                 .Throw( new UnauthorizedException() );

    Controller controller = new Controller( view );
    controller.AuthenticateUnitAccount += authenticator.Authenticate;

    controller.OnAuthenicateAccount()

    authenticator.VerifyAllExpectations();
}
于 2008-12-16T20:35:24.297 回答