2012-03-14 53 views
5

我是一個「初學者」在TDD和什麼我試圖找出是如何單元測試的ViewModels ...測試視圖模型的PropertyChanged事件

我想,以確保財產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"); 
    } 
} 

回答

4

這幾乎是你如何做到這一點。考慮到它非常簡單(和無聊)的代碼,在這裏沒有太多的事情要做。將它包裝在您自己的可重用的庫/工具中可能是值得的。或者更好,use existing code

+0

我已經重構它使用[TestCase的],並使其更通用...感謝您的建議 – 2012-03-15 04:21:15

1

我自己對這類事情的「最小」測試略有不同。我通常不會檢查事件是否發生,而是通過驗證一次

+0

好一點 - 值得考慮的 – 2012-03-15 04:19:42

1

花崗岩的測試框架可以讓你寫測試是這樣的:

[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的工作。

+0

謝謝,我會檢查出花崗岩 - 這看起來對我來說更像是一個集成測試,但肯定是我想要涵蓋的內容 – 2012-03-15 04:20:33

+0

集成測試?不,它不會與任何外部服務或數據庫交談。 – 2012-03-15 06:08:19

0

我做了一個簡單的類,你可以使用這個: github

它使用反射來determin如果當值設置公共財產都提出了一個屬性更改事件。

例子:


[TestMethod] 
public void Properties_WhenSet_TriggerNotifyPropertyChanged() 
{ 
    new NotifyPropertyChangedTester(new FooViewModel()).Test(); 
}