Raising an Event

Sometimes writing unit test it may be necessary to raise an event of fake-object. Example below demonstrates a raising event (with declared EventHandler delegate):

// Arrange
var isCalled = false;
shapeFake.Drawed += (sender, args) => isCalled = true;

// Act
Event.Raise(() => shapeFake.Drawed += Event.Handler());

// Assert
Assert.IsTrue(isCalled);

You can also raise events, passing arguments to the event handler. For example, if the event is declared in such a way:

event EventHandler<DrawEventArgs> Drawing;

with DrawEventArgs arguments :

/// <summary>
/// Arguments for drawing event handlers.
/// </summary>
public class DrawEventArgs : EventArgs
{
    /// <summary>
    /// Cancel drawing if true.
    /// </summary>
    public bool CancelDrawing { get; set; }
}

then such an event raising in the unit test will take place as follows:

var args = new DrawEventArgs { CancelDrawing = true };
Event.Raise(() => shapeFake.Drawing += Event.Handler(shapeFake, args));

In addition, True Fakes work in a similar way to the custom event delegates declared (not an EventHandler). For example, if the event is declared as follows:

event Action<bool> Drawed;

then such an event raising will take place as follows:

Event.Raise(() => shapeFake.Drawed += Event.HandlerAsDelegate<Action<bool>>(false));