Search This Blog

Thursday, 17 November 2022

Unit Testing if an Event using NUnit

This is for Unit Test Developers, who write test cases for given features. Here we shall see how to unit test events, and internally how events work.

Events follow the pub-sub pattern. In this pattern, in .Net , internally a delegate is used to collect methods that subscribe to the event variable.

Let's take an example. If we consider the windows forms button control, it contains the click event.


The click event internally uses a delegate called Event Handler. The structure of the Event Handler delegate looks like this.



To attach a method to an event, we use the  '+=' operator.


Here we have used lambda expressions.


So how do we test such a scenario.

The strategy is simple. In the testcase, attach a dummy function to the event and then trigger it. By doing this we can assert if the event has occurred or not.


Hope this helps.

No comments:

Post a Comment