25% developed

How to Use Rhino Mocks/Testing Events

From Wikibooks, open books for an open world
Jump to navigation Jump to search

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:

 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.
     // create our presenter
     Presenter presenter = new Presenter(viewMock);
     // no indication from the user yet.
     // simulate user action by raising event on mocked interface.
     raiser.Raise(viewMock, EventArgs.Empty);
     // user is known to be alive and kicking.