转到内容

如何使用 Rhino Mocks/测试事件

25% developed
来自教科书,面向开放世界的开放书籍

Rhino Mocks 可用于测试接口上的事件。例如,让我们假设一个表示编辑器视图的接口。这反过来可能由 WinForms 应用程序中未经测试的轻量级用户控件实现

 public interface IView
 {
   event EventHandler UserClickedSomething;
 }

我们将测试此视图的演示器类。断言由于引发该事件而导致采取某种动作的 NUnit 测试可能如下所示

 [Test]
 public void UserClickedSomething_Handled()
 {
     MockRepository mocks = new MockRepository();
     
     // create the mock
     IView viewMock = (IView)mocks.CreateMock(typeof(IView));
 
     // indicate that we expect an event handler to be attached.
     // in doing so, we obtain an IEventRaiser instance.
     viewMock.UserClickedSomething += null;
     IEventRaiser raiser = LastCall.IgnoreArguments().GetEventRaiser();
 
     // we've finished recording.
     mocks.ReplayAll();
 
     // create our presenter
     Presenter presenter = new Presenter(viewMock);
 
     // no indication from the user yet.
     Assert.IsFalse(presenter.IsUserAlive);
 
     // simulate user action by raising event on mocked interface.
     raiser.Raise(viewMock, EventArgs.Empty);
 
     mocks.VerifyAll();
 
     // user is known to be alive and kicking.
     Assert.IsTrue(presenter.IsUserAlive);
 }
华夏公益教科书