When coding in WPF with the MVVM pattern, it's common to see a lot of property get/set statements that raise an event, which can then be picked up by the UI layer.
public string Address
{
get
{
return _address;
}
set
{
_address = value;
OnPropertyChanged("Address");
}
}
Many classes contain tens of these. The level of boilerplate code required is seen as a necessary evil by MVVM advocates.
However, one of the key advantages of MVVM over traditional code-behind models is that it's much easier to unit test. This is fine for functions and such, but there's a lot of uncovered code due to the getting and setting of these properties which is often done from the UI layer.
It made me wonder about the value of unit testing them. There's a valuable thing to check here: if a property doesn't raise the expected event, it can have severe repercussions for the functionality of the application. But on the other hand, changes to these properties are rare, and unit testing them would result in even more boilerplate code which would need to be maintained.
Are trivial functions like this worth the additional overhead of writing and maintaining tests?
EDIT: A commenter asked about how you'd unit test this. Here's an example from another property that I tested because the setter does more than just raise an event:
Mock<IReciprocateRepository> repMock = GetMockRepository();
CampaignViewModel cVm = new CampaignViewModel(repMock.Object);
List<string> receivedEvents = new List<string>();
cVm.PropertyChanged += (sender, e) => receivedEvents.Add(e.PropertyName);
cVm.LoadHistory();
Assert.IsTrue(receivedEvents.Contains("MemberItems"));
PropertyChanged
event, due to a misspelling in the magic string. All properties that raisePropertyChanged
now get tested. When in doubt, write the test.PropertyName
from thePropertyChangedEventArgs
in a local variable. The assert compares the property name that is expected to the property name that got passed.