Introduction
One common mistake I make in programming classes that implement INotifyPropertyChanged is to forget to raise the change event in the property setter. Therefore I added this to the list of things I commonly unit test.
For example, given the following class that implements INotifyPropertyChanged:
Public NotInheritable Class AggregateModel
Implements System.ComponentModel.INotifyPropertyChanged
<DataMember(Name:=NameOf(Name))>
Private ReadOnly m_name As String
<XmlAttribute(AttributeName:="AggregateName")>
Public ReadOnly Property Name As String
Get
Return m_name
End Get
End Property
<DataMember(Name:=NameOf(KeyName))>
Private m_keyName As String = "Key"
<XmlAttribute(AttributeName:="KeyName")>
Public Property KeyName As String
Get
Return m_keyName
End Get
Set(value As String)
If Not (m_keyName.Equals(value)) Then
m_keyName = value
OnPropertyChanged(NameOf(KeyName))
End If
End Set
End Property
End Class
A unit test would look like
<TestMethod>
Public Sub Keyname_ChangeNotification_TestMethod()
Dim expected As String = "KeyName"
Dim actual As String = "Not Set"
Dim testObj As New AggregateModel("TestObject")
AddHandler testObj.PropertyChanged, New PropertyChangedEventHandler(
Sub(ByVal sender As Object, ByVal e As PropertyChangedEventArgs)
actual = e.PropertyName
End Sub )
testObj.KeyName = "My key"
testObj = Nothing
Assert.AreEqual(expected, actual)
End Sub