Insights and outlooks on software development


How to use Rhino Mocks to expect event raises

Thursday, February 21, 2008 by Thomas L

Let's say that you have a repository that raises events whenever an entity is saved, and that you'd like to test that functionality. This is actually quite simple when using Rhino Mocks. Try to follow me here:

Create a generic IEventHandler interface, so that it can listen to all events:


public interface IEventHandler<T> { void OnEventRaised(object sender, T eventargs); }

Then we look at the test method:

[Test] public void RepositoryShouldRaiseEventUponSaving() { //mocks (probably best to create in the [SetUp] MockRepository _mocks = new MockRepository(); IEventHandler<EventArgs> eventHandler = _mocks.CreateMock<IEventHandler<EventArgs>>(); IOrder order = _mocks.Stub<IOrder>(); //system-under-test (ditto) OrderRepository repository = new OrderApplication.OrderRepository(); //listen to the event repository.OrderSaved += new EventHandler<EventArgs>(eventHandler.OnEventRaised); using (_mocks.Record()) { // Create an expectation on our mock's OnEventRaised method eventHandler.OnEventRaised(repository, EventArgs.Empty); } using (_mocks.Playback()) { repository.Save(order); } }

So basically, what we've done here is to create a mock of the IEventHandler interface, and we then created an expectation saying that that mock's OnEventRaised method should be called. It's as simple as that.

It's quite easy, actually, to do this for events with other arguments than EventArgs; just create a mock instance with another type argument.

Technorati tags: ,,,

Filed under having  

0 kommentarer: