Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PropertyChanged event testing: is this a good way?

I'm developing WPF applications using MVVM pattern. I have ViewModel with code like this:

public bool EditModeEnabled
{
    get { return _EditModeEnabled; }
    set
    {
        _ModeEditModeEnabled = value;
        OnPropertyChanged("EditModeEnabled");
        OnPropertyChanged("CommentTextBoxVisibility");
    }
}

OnPropertyChanged is virtual method of base class which just raise PropertyChanged event. I want to test PropertyChanged event raising and there my test method:

public void EditModeEnabledTest()
{
    var imageViewModel = TestHelper.GetTestImageViewModel();
    var firedEvents = new List<string>();
    imageViewModel.PropertyChanged += ((sender, e) => firedEvents.Add(e.PropertyName));
    imageViewModel.Mode = true;
    Assert.AreEqual(firedEvents.Count, 2);
    Assert.IsTrue(firedEvents.Contains("EditModeEnabled"));
    Assert.IsTrue(firedEvents.Contains("CommentTextBoxVisibility"));
    ...
}

Is it a good way to test ProprtyChanged event?

like image 853
bniwredyc Avatar asked Dec 08 '09 08:12

bniwredyc


People also ask

What is the purpose of INotifyPropertyChanged?

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed. For example, consider a Person object with a property called FirstName .

How do you implement PropertyChanged?

To implement INotifyPropertyChanged you need to declare the PropertyChanged event and create the OnPropertyChanged method. Then for each property you want change notifications for, you call OnPropertyChanged whenever the property is updated.

What is Propertychangedeventhandler C#?

Represents the method that will handle the PropertyChanged event raised when a property is changed on a component.


1 Answers

I use a little Fluent API for doing exactly that. It allows you to write tests like this:

var imageViewModel = TestHelper.GetTestImageViewModel();
imageViewModel.ShouldNotifyOn(s => s.EditModeEnabled)
    When(s => s.Mode = true);

Besides being succinct, I prefer this approach because it's type-safe - no string values to keep in sync with your API.

To test that the event is being raised for more than one property, you can just write another test that does this. This will give you many tests, but each will be very small and you avoid Assertion Roulette.

like image 55
Mark Seemann Avatar answered Sep 18 '22 15:09

Mark Seemann