The way I test events is as follows:
Suppose this is your object:
public class MyEventRaiser { public event EventHandler<string> MyEvent = delegate { }; public void Process(string data) {
So your subject is under test: MyEventRaiser , and you want to test the Process method. You need to check that the event occurs when certain conditions are met, otherwise the event should not be raised.
For this, I use this framework (I always use it in my tests ) FluentAssertions , this framewrok can be used with any test engine, such as MSTest, NUnit, MSpec, XUnit, etc.
The tests look like this:
[TestClass] public class CustomEventsTests { [TestMethod] public void my_event_should_be_raised() { var sut = new MyEventRaiser(); sut.MonitorEvents(); sut.Process("Hello"); sut.ShouldRaise("MyEvent").WithSender(sut); } [TestMethod] public void my_event_should_not_be_raised() { var sut = new MyEventRaiser(); sut.MonitorEvents(); sut.Process(null); sut.ShouldNotRaise("MyEvent"); } }
You need to use the following namespaces:
using FluentAssertions; using FluentAssertions.EventMonitoring;
source share