When testing event-driven code in C#, I would like to make sure my assertions don't execute until after the object under test has had a chance to handle an event. Currently, I am using an AutoResetEvent
object to pause execution until an event is fired like this:
private MyClassDependency testObjectDependency = new MyClassDependency();
private MyClass testObject = new MyClass(testObjectDependency);
private AutoResetEvent eventLock = new AutoResetEvent(false);
void handle(object sender, EventArgs e)
{
eventLock.Set();
}
[Test()]
public void DoSomethingTest()
{
testObjectDependency.Event += handle;
testObject.DoSomething();
eventLock.WaitOne();
testObjectDependency.Event -= handle;
testObject.IsSomethingDone.Should().Be.True();
}
While running the debugger, I set breakpoints in the test event handler and in testObject
's event handler, and I can see that the test handler fires first, then the handler I'm trying to test begins, and then the test fails before the real handler completes.
How should I change this setup so that the handler in my test will not be called until after all other handlers have been called? I'm using Visual Studio 2013, .NET 4.0 Client, NUnit 2.6.3, and Should.Fluent 1.0.
This question is somewhat similar to this previous one, except that here I want to guarantee that all other event handlers have completed first.
Edit:
Thanks to a few helpful comments, I went back to my code and realized that the problem was in my test setup. This was my original setup code:
[SetUp]
public void SetupDeviceController()
{
dev = new TestDevice();
dc = new DeviceController(dev);
dev.Read += dev_Read;
dc.Open();
}
A matching dev.Read -= dev_Read;
appears in the [TearDown]
method.