代码之家  ›  专栏  ›  技术社区  ›  nportelli

犀牛模型3.5的假人…我

  •  0
  • nportelli  · 技术社区  · 16 年前

    我正在尝试使用犀牛模型3.5和新的lambda符号来模拟一些测试。我读过 this 但是还有很多问题。有没有完整的例子,特别是对于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();
        }
    

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

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

    1 回复  |  直到 16 年前
        1
  •  2
  •   tvanfosson    16 年前

    我假设这是你的一个控制器。此外,我假设您有一种通过构造函数或setter传递视图数据的方法,并且您有一种注册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类包含与处理程序签名匹配的身份验证方法。因为您需要知道是否调用了这个方法,所以您需要模拟它,而不是使用存根来确保它是用正确的参数调用的,等等。您会注意到,我是直接调用这个方法,而不是引发一个事件。因为您只需要在这里测试代码,所以不需要测试在引发事件时会发生什么。你可能想在其他地方测试一下。这里,我们只想知道用正确的参数调用正确的方法。

    对于失败,你可以做如下的事情:

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