Unit Test PropertyChanged

1 minute read

One of the basic stuff you wanna test as a client side developer, is that all of your UI bounded classes aka Controller, Model, ViewModel, Presenter, PresentationModel, or the code behind of your view if your just having fun.

Let's assume we have a person class with a name property:

public class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

private string _name;

public virtual string Name
{
get { return _name; }
set { _name = value;
FirePropertyChanged("Name");
}
}

protected virtual void FirePropertyChanged(string propertyName)
{
var handlers = PropertyChanged;
if (handlers != null)
{
handlers(this, new PropertyChangedEventArgs(propertyName));
}
}
}
The simplest way to perform this test is to write this code:

[TestFixture]
public class PersonTest
{
[Test]
public void SetName_SomeNewString_FirePropertyChanged()
{
Person person = new Person();
string changedPropertyName = string.Empty;
person.PropertyChanged += (sender, args) => changedPropertyName = args.PropertyName;
person.Name = "Test";
Assert.AreEqual("Name", changedPropertyName);
}
}

Leave a Comment