How to Use Rhino Mocks/Testing Events

Rhino Mocks can be used to test events on interfaces. For example, let's assume an interface that represents an editor view. This might in turn be implemented by an untested, lightweight user control in a WinForms application:

 public interface IView
 {
   event EventHandler UserClickedSomething;
 }

We'll be testing the presenter class of this view. An NUnit test that asserts some action takes place due to this event being raised might look like this:

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