Hi all,
I've been playing around with an alternate syntax for raising events
from mocks, based on an event subscription in a delegate (the
mock.Raise(...) call):
[Fact]
public void Suggestion_for_raising_events() {
var mock = MockRepository.GenerateMock<IDoSomething>();
var wasCalled = false;
mock.SomethingDone += (sender, e) => wasCalled = true;
mock.Raise(x => x.SomethingDone += null, mock, EventArgs.Empty);
Assert.True(wasCalled);
}
It reads fairly clearly to me, but I'm fairly new to mocking and Rhino
Mocks so I may have an odd perspective on this. I've implemented it by
abusing existing Rhino Mocks methods (3.5 beta) and .NET 3.5
extensions methods, but am keener on the syntax than the
implementation:
public static class EventRaiserExtensions {
private static IEventRaiser
GetEventRaiserFromSubscription<TEventSource>(
this TEventSource mock, Action<TEventSource>
eventSubscription) {
return mock
.Stub(eventSubscription)
.IgnoreArguments()
.GetEventRaiser();
}
public static void Raise<TEventSource>(this TEventSource mock,
Action<TEventSource> eventSubscription, object sender, EventArgs args)
{
var eventRaiser = GetEventRaiserFromSubscription(mock,
eventSubscription);
eventRaiser.Raise(sender, args);
}
public static void Raise<TEventSource>(this TEventSource mock,
Action<TEventSource> eventSubscription, params object[] args) {
var eventRaiser = GetEventRaiserFromSubscription(mock,
eventSubscription);
eventRaiser.Raise(args);
}
public static void Raise<TEventSource>(this TEventSource mock,
Action<TEventSource> eventSubscription) {
var eventRaiser = GetEventRaiserFromSubscription(mock,
eventSubscription);
eventRaiser.Raise(mock, EventArgs.Empty);
}
}
Be interested to get feedback on this.
I wrote up the details (including the traditional approaches to
raising events) here:
http://davesquared.blogspot.com/2008/06/yet-another-way-of-raising-events-from.html
Regards,
David