2

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

  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()哪个用于更新 UI。

4

3 回答 3

3

一个简单的方法是这样做:

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

compassLogData.ThreadId = "[11]";
Assert.True(notified);
于 2013-02-05T11:08:49.490 回答
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 添加到列表中可以检查它被触发的次数等。

通常我真的看不出测试那个小逻辑的意义。

于 2013-02-05T11:13:04.800 回答
0

您必须处理属性更改事件,并检查是否为正确的属性触发。

[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();
        }
    }
}
于 2013-02-05T11:11:10.993 回答