我假设这是你的一个控制器。此外,我假设您有一种通过构造函数或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();
}