单元测试NotifyPropertyChanged()

时间:2013-02-05 11:01:56

标签: c# unit-testing

测试此属性的最佳方法是什么:

  public string ThreadId {
        get { return _threadId; }
        set {
            _threadId = value;
            NotifyPropertyChanged();
        }
    }

到目前为止我有这个测试:

    [Fact]
    public void ThreadIdTest() {
        compassLogData.ThreadId = "[11]";
        const string expected = "[11]";
        string actual = compassLogData.ThreadId;
        Assert.Equal(expected, actual);
    }

但是我需要一个人来测试NotifyPropertyChanged() 更新用户界面。

3 个答案:

答案 0 :(得分:3)

一种简单的方法是:

var notified = false;
compassLogData.PropertyChanged += (s, e) =>
{
    if(e.PropertyName == "ThreadId")
        notified = true;
};

compassLogData.ThreadId = "[11]";
Assert.True(notified);

答案 1 :(得分:1)

测试事件时,我使用这种模式:

[Test]
public void PropertyChangeTest()
{
    var viewModel = new ViewModel();
    var args = new List<PropertyChangedEventArgs>();
    viewModel.PropertyChanged += (o, e) => args.Add(e);
    viewModel.ThreadId = "[11]";
    Assert.AreEqual("ThreadId",args.Single().PropertyName);
}

将eventargses添加到列表可以检查它被触发的次数等。

通常我真的没有看到测试那个小逻辑的重点。

答案 2 :(得分:0)

您必须处理property-changed-event,并检查是否为正确的属性触发了。

[Fact]
public void ThreadIdTest() {
    compassLogData.ThreadId = "[11]";
    var previousValue = compassLogData.ThreadId; // Question: how is this object set?
    bool propertyWasUpdated = false;
    compassLogData.PropertyChanged += (s, e) => {
        if (e.PropertyName == "ThreadId") {
            propertyWasUpdated = true;
        }
    };

    const string expected = "[12]";
    compassLogData.ThreadId = expected;
    string actual = compassLogData.ThreadId;

    Assert.Equal(expected, actual);
    ASsert.IsTrue(propertyWasUpdated);
}

另外,您应该只在值实际更改时触发事件。我通常这样实现它:

public string ThreadId {
    get { return _threadId; }
    set {
        if (value != _threadId) {
            _threadId = value;
            NotifyPropertyChanged();
        }
    }
}