Raise
Use Mock.Raise to fire a mock event directly from your test code, at the exact point in the test you choose. You can raise custom or standard events.
Mock.Raise differs from Raises: Raises is chained on Mock.Arrange and fires the event automatically when a specific method is called. Mock.Raise fires the event immediately when you call it in the test.
Raising Custom Events
Assume we have the following interface:
public delegate void CustomEvent(string value);
public interface IFoo
{
event CustomEvent CustomEvent;
}Next is an example on how to use Raise to fire custom event.
[TestMethod]
public void ShouldInvokeMethodForACustomEventWhenRaised()
{
string expected = "ping";
string actual = string.Empty;
// Arrange
var foo = Mock.Create<IFoo>();
foo.CustomEvent += delegate(string s)
{
actual = s;
};
// Act
Mock.Raise(() => foo.CustomEvent += null, expected);
// Assert
Assert.AreEqual(expected, actual);
}We use Raise to raise foo.CustomEvent and pass "ping" to it. Before acting we have attached a delegate to the event. Executing the delegate will result in assigning the passed string to actual. Finally, we verify that expected and actual have the same value.
Raising Standard Events
Assume we have the following system under test:
public interface IExecutor<T>
{
event EventHandler<FooArgs> Done;
}
public class FooArgs : EventArgs
{
public FooArgs()
{
}
public FooArgs(string value)
{
this.Value = value;
}
public string Value { get; set; }
}An example on how to use Raise to fire standard event would look like this:
[TestMethod]
public void ShouldRaiseEventWithStandardEventArgs()
{
string actual = null;
string expected = "ping";
// Arrange
var executor = Mock.Create<IExecutor<int>>();
executor.Done += delegate(object sender, FooArgs args)
{
actual = args.Value;
};
// Act
Mock.Raise(() => executor.Done += null, new FooArgs(expected));
// Assert
Assert.AreEqual(expected, actual);
}Here we use Raise to raise a standard event - executor.Done accepting FooArgs object. The attached delegate sets the Value property in FooArgs object to the variable actual. Finally, we verify that expected and actual have the same value.