Ayende @ Wiki

The event raiser is a solution to a common problem, how do you raise an event from an interface? Let us consider this code:

public interface IView
{
   event EventHandler Load;
}

public class Presenter { public bool OnLoadCalled = false;

public Presenter(IView view) { view.Load+= OnLoad; }

private void OnLoad(object sender, EventArgs e) { OnLoadCalled = true; //the code that we would like to test } }


How are we going to test this code? We can utilize the usual event handling mechanisms to verify that the presenter was registered, but notice that the OnLoad method is private, so we can't access it normally. We would like to raise the event, so the method would be called.

IEventRaiser is the answer to that. As usual, we would like to deal with strongly typed objects, so we need to have some way to mark which event we would like to use.

Getting IEventRaiser Implementation:

Test
public void RaisingEventOnView()
{
   IView view = mocks.CreateMock<IView>();
   view.Load+=null;//create an expectation that someone will subscribe to this event
   LastCall.IgnoreArguments();// we don't care who is subscribing
   IEventRaiser raiseViewEvent = LastCall.GetEventRaiser();//get event raiser for the last event, in this case, View
}


This coincides with testing that someone is subscribing to the event, so the somewhat awkward syntax doesn't matter that much. Now, how do I raise the event?

Test
public void RaisingEventOnView()
{
   IView view = mocks.CreateMock<IView>();
   view.Load+=null;//create an expectation that someone will subscribe to this event
   LastCall.IgnoreArguments();// we don't care who is subscribing
   IEventRaiser raiseViewEvent = LastCall.GetEventRaiser();//get event raiser for the last event, in this case, View

mocks.ReplayAll();

Presenter p = new Presenter(view); raiseViewEvent.Raise();

Assert.IsTrue(p.OnLoadCalled ); }


So, that was simple :-)

Note: Event Subscribers, like all other information on a mock object, will be cleared if BackToRecord(mock) or BackToRecordAll() are called.

Up: Rhino Mocks Documentation
Next: Rhino Mocks Properties

ScrewTurn Wiki version 2.0 Beta. Some of the icons created by FamFamFam.