Testing Event Handlers in C#
When working with software engineering teams, I’m always interested in how I can assist with making their lives easier or how to help them continuously improve quality and productivity in their daily work.
In this article I’ll describe a technique for improving testability of events in C#. I will show you how to invoke events from outside the class in which they are declared in. This can be useful when you want to test event call-backs that are private inside the class under test including whether the call-backs are registered correctly.
Let’s assume, we have a class like the following:
The we may be tempted to write a test like the following:
However, you will find that your compiler report a compile error for the line starting with “cut.Received( … )”:
error CS0070: The event ‘ClassWithOneEventHandler.Received’ can only appear on the left hand side of += or -= (except when used from within the type ‘ClassWithOneEventHandler’)
How to solve this problem? How can we keep the test as simple as possible and still invoke the “Received” event?
Admittedly, the class I’m using as an example is trivial. In practice we’ll typically have something more complicated and probably we won’t handle tracing the way it is done in this class. However, this article is not about whether the class under test provides sufficient value or contains beautiful code. Here we want to focus on how we can test that the private event call-back has in fact properly been added to the event and that it behaves as expected (within limits).