Search The Blog
About this site

@RoyOsherove

Subscribe!

This site aims to connect all the dots of my online activities - from tools, books blogs and twitter accounts, to upcoming conferences, engagements and user group talks.

from 5whys.com
Twitter: @RoyOsherove
My Book: The Art of Unit Testing
Latest Posts
« SilverUnit Project Template and new version | Main | DateTime.LastYear »
Saturday
May232009

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

PrintView Printer Friendly Version

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>