正在测试ViewModel PropertyChanged事件
本文关键字:PropertyChanged 事件 ViewModel 测试 | 更新日期: 2023-09-27 18:27:52
我是TDD的"初学者",我想弄清楚的是如何对视图模型进行单元测试。。。
我想确保属性ProeprtyChanged事件被激发。。。我用nunit做了以下测试。
[Test]
public void Radius_Property_Changed()
{
var result = false;
var sut = new MainViewModel();
sut.PropertyChanged += (s, e) =>
{
if (e.PropertyName == "Radius")
{
result = true;
}
};
sut.Radius = decimal.MaxValue;
Assert.That(result, Is.EqualTo(true));
}
这是最干净的方法吗,还是有更好的方法来测试的性能
我正在测试的属性的视图模型中的代码片段如下。。。
public decimal Radius
{
get { return _radius; }
set
{
_radius = value;
OnPropertyChanged("Radius");
}
}
这几乎就是您的操作方法。这里没有太多其他事情可做,因为它是非常简单(而且无聊)的代码。将其封装在您自己的可重用库/工具中可能是值得的。或者更好的是,使用现有的代码。
我自己对这类事情的"最小"测试略有不同。我通常会验证是否引发了一次,而不是检查是否引发了事件。
[TestMethod]
public void ChangeTrackingModelBase_BasicFunctionalityTest()
{
var person = new ChangeTrackingPerson();
var eventAssert = new PropertyChangedEventAssert(person);
Assert.IsNull(person.FirstName);
Assert.AreEqual("", person.LastName);
eventAssert.ExpectNothing();
person.FirstName = "John";
eventAssert.Expect("FirstName");
eventAssert.Expect("IsChanged");
eventAssert.Expect("FullName");
person.LastName = "Doe";
eventAssert.Expect("LastName");
eventAssert.Expect("FullName");
person.InvokeGoodPropertyMessage();
eventAssert.Expect("FullName");
person.InvokeAllPropertyMessage();
eventAssert.Expect("");
}
http://granite.codeplex.com/SourceControl/list/changesets
它是基于MSTest的,但是您可以很容易地重写它来使用NUnit。
我制作了一个简单的类,您可以使用它:github
它使用反射来确定在值设置为公共属性时是否引发了属性更改事件。
示例:
[TestMethod]
public void Properties_WhenSet_TriggerNotifyPropertyChanged()
{
new NotifyPropertyChangedTester(new FooViewModel()).Test();
}