Unit testing INotifyPropertyChanged [tip]





0/5 (0 vote)
How to unit test a class that implements INotifyPropertyChanged
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
''' <summary>
''' The unique name by which the event sourcing model is known
''' </summary>
''' <remarks>
''' This is used to refer to this model in code and also in the default filename
''' </remarks>
<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"
''' <summary>
''' The name by which the property which provides the unique key for this aggregate is known
''' </summary>
''' <remarks>
''' This defaults to "Key" if there is no meaningful business key name
''' </remarks>
<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