Testing Event Handlers in C#

Using reflection to improve testability

Manfred Lange
7 min readApr 10, 2022
Compiler Error csharp(CS0070)

Introduction

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:

--

--

Manfred Lange
Manfred Lange

Written by Manfred Lange

CTO at MacroActive https://www.macroactive.com. I write about improving flow of value in software engineering. LinkedIn https://www.linkedin.com/in/manfredlange

No responses yet