Ayende @ Wiki

Edit

Test Subscribe To Event

Here is how you check that the object under test subscribes to an event on a mock object:
public interface IWithEvents 
{ 
     event EventHandler Blah; 
     void RaiseEvent(); 
}  

[Test] public void VerifyingThatEventWasAttached() { MockRepository mocks = new MockRepository(); IWithEvents events = mocks.CreateMock<IWithEvents>(); With.Mocks(mocks).Expecting(delegate { events.Blah += new EventHandler(events_Blah); }) .Verify(delegate { MethodThatSubscribeToEventBlah(events); }); }

public void MethodThatSubscribeToEventBlah(IWithEvents events) { events.Blah += new EventHandler(events_Blah); }

[Test] public void VerifyingThatEventWasAttached_AAA() { var events = MockRepository.GenerateMock(); events.Blah += MethodThatSubscribeToEventBlah; events.AssertWasCalled(x => x.Blah += Arg.Is.Anything); }

You just record that you want to subscribe to the event and then run the code that is supposed to subscribe to it.

Edit

Test Event Was Raised

Now, let's try do it from the other side, how do we check that an event was raised? Well, that is a little more complicated, but not very much so. What we need to do create an interface with a matching method name, create a mock from this interface, and then just subscribe to the event and record any expectations regarding the method. As usual, the code is clearer then the explanation:
public interface IEventSubscriber 
{ 
     void Handler(object sender, EventArgs e); 
} 
public class WithEvents : IWithEvents 
{ 
     #region IWithEvents Members  
     public event System.EventHandler Blah;

public void RaiseEvent() { if (Blah!=null) Blah(this, EventArgs.Empty); } #endregion }

[Test] public void VerifyingThatAnEventWasFired() { MockRepository mocks = new MockRepository(); IEventSubscriber subscriber = mocks.CreateMock<IEventSubscriber>(); IWithEvents events = new WithEvents(); // This doesn't create an expectation because no method is called on subscriber!! events.Blah+=new EventHandler(subscriber.Handler); subscriber.Handler(events, EventArgs.Empty); mocks.ReplayAll(); events.RaiseEvent(); mocks.VerifyAll(); }
One thing to notice here is that subscribing to the event does not create an expectation, since no action is taken on the subscriber instance. Then, to create an expectation that the method will be raised with the specified arguments, we just call the method we just subscribed. Since the raised event will eventually resolve itself to the same method call, everything works as expected.

Rhino Mocks also supports raising events, using the IEventRaiser interface.

Up: Rhino Mocks Documentation
Next: Rhino Mocks IEventRaiser

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