Here's a little method I came up with recently to test the execution of events. You may not ever need to test to see that an event fires, because you have some other state that you can check. However, that is not always the case. Here is how I approached it using the unit testing provided with the developer's team editon of Visual Studio.
The first thing I did was add a wait handle object inside the definition of my unit test class. Specifically, I chose a ManualResetEvent for the most control, but other types of wait handles may work fine.
private static ManualResetEvent _waitHandle;
The next step was to add code for the class initialize and cleanup methods. I need to create my wait handle and after I finish running my tests I want to make sure that I release any resources tied-up by the wait handle. Additionally, after a test is run I want to make sure that the wait handle is in an unsignalled state. Therefore, I need to provide a test cleanup method.
//Use ClassInitialize to run code before running the first test
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
_waitHandle = new ManualResetEvent(false);
}
//Use ClassCleanup to run code after all tests in a class have run
[ClassCleanup()]
public static void MyClassCleanup()
{
if (_waitHandle != null)
_waitHandle.Close();
}
//Use TestCleanup to run code after each test has run
[TestCleanup()]
public void MyTestCleanup()
{
_waitHandle.Reset();
}
That's pretty much it except for the logic in the code itself. In that code, you create your event handler, run the action that will trigger the event, and then wait for the ManualResetEvent to be signalled. It is advisable to provide an arbitrary yet realistic value for a timeout so that your test doesn't run forever if the event isn't fired.
[TestMethod()]
public void EventExecutedTest()
{
MyObject target = new MyObject();
// TODO: add additional declarations as needed for test
target.EventExecuted += (sender, e) => _waitHandle.Set();
// TODO: perform actions that need to trigger the event
bool result = _waitHandle.WaitOne(3000, true);
Assert.IsTrue(result);
}
As you can see there's not too much to it. This is a simple mechanism to unit tests events when it makes sense.