Unit testing events – Asserting event rasing

I was working on a Silverlight application where property setter raises PropetyChanged events for other read only properties that needs to be updated. Something like,

private List<User> users;
public List<User> Users
{
      get
      {
           return users;
      }
      set
      {
           users = value;
           Changed("Users");
           Changed("EnableDisableButton");
           Changed("UsersCount");
      }
}

private void Changed(string propertyName)
{
      if (PropertyChanged == null) return;
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

Here is how I came up with a test case that asserts the proper events are raised in proper order.

[Test]
public void ProperEventsAreRaisedWhenUsersChanges()
{
       var propertiesChanged = new List<string>();
       var model = new UserModel();
       model.PropertyChanged += (sender, args) => propertiesChanged.Add(args.PropertyName);
       model.Users = new List<User>();
       propertiesChanged[0].ShouldBe("Users");
       propertiesChanged[1].ShouldBe("EnableDisableButton");
       propertiesChanged[2].ShouldBe("UsersCount");
}

ShouldBe() is an extension method which does Assert.That internally.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s