Roy Osherove

View Original

Testing that an event was raised

This question keeps coming up: “How can I test that an event was actually raised from my class under test?”

actually, there is an easy way to check if an event was raised.
you subscribe to the event in your test, and in the event handler you set a boolean flag to true. then you just assert on the flag.
here is a quick example:

Code:

public void Test()
{
bool wasRaised=false;
var button = new Button;
button.Click += ()=> wasRaised=true;
button.DoSomethingThatShouldHaveTriggeredTheEvent();
Assert.IsTrue(wasRaised);
}

 

If you feel less comfortable using lambdas:

public void Test()
{
bool wasRaised=false;
var button = new Button;
button.Click += delegate

{

wasRaised=true

};


button.DoSomethingThatShouldHaveTriggeredTheEvent();
Assert.IsTrue(wasRaised);
}

 

Unfortunately, with VB.NET’s current version, doing this in a single method is next to impossible, so you are forced to register to the event with a method at the class level, and check that:

 

Code (VB.NET):

dim wasRaised as Boolean=false;

public sub test()

wasRaised=false
dim button = new Button()
AddHandler( button.Click , AddressOf(OnClick))

button.DoSomethingThatShouldHaveTriggeredTheEvent()
Assert.IsTrue(wasRaised);

end sub

public sub OnClick(source as object,e as EventArgs)

wasRaised=true

end sub