Martin Christiansen Martin Christiansen - 10 months ago 73
C# Question

Moq: How to raise an event with non-null sender

Consider this interace:

public interface IFoo
event EventHandler SomethingHappened;

With Moq, I make a mock of the interface, and now I want to raise the event:

var myMock = new Mock<IFoo>();
myMock.Raise( x=>x.SomethingHappened += null, EventArgs.Empty );

This works perfectly, but the problem is that the subscriber expects sender to be something (the IFoo that raises the event, actually) and not just null.

Therefore I want to raise the event like this:

myMock.Raise(x=>x.SomethingHappened += myMock.Object, EventArgs.Empty );

but the compiler will not allow that - it seemingly only accepts null as sender. Why is that? Is there a way do do what I really want?

Answer Source

Assuming that you are using .Net 4.5, there's a change in definition of the EventHandler<TEventArgs> delegate, check the links for 4.5 and 4.0, this ensures that though you are using a type of IFoo, which may not be assignable from EventArgs, still compiler doesn't complain as it would have in 4.0, but other aspect would be Moq framework would consider event as a standard delegate not event pattern, which needs to be called as:

myMock.Raise(x=>x.SomethingHappened += null,myMock.Object, EventArgs.Empty);

x.SomethingHappened += null, which tell the Moq framework, which event / delegate to invoke and rest will be standard argument in the form object sender, EventArgs e