2012-09-30 36 views

回答

4

我測試賽的方式如下:

假設這是你的對象:

public class MyEventRaiser 
{ 
    public event EventHandler<string> MyEvent = delegate { }; 

    public void Process(string data) 
    { 
     // do something interestuing 

     Thread.Sleep(2000); 

     if (!string.IsNullOrEmpty(data)) 
     { 
      this.MyEvent(this, data + " at: " + DateTime.Now.ToString()); 
     } 
    } 
} 

因此你的主題下測試是:MyEventRaiser,你要測試的方法Process。您需要測試在滿足特定條件時引發的事件,否則不應提升事件。

要做到這一點,我用這個框架(我用在我的測試總是)FluentAssertions,這framewrok可以與任何測試引擎像MSTest的,NUnit的,MSpec,的xUnit使用等

測試看起來像:

[TestClass] 
public class CustomEventsTests 
{ 
    [TestMethod] 
    public void my_event_should_be_raised() 
    { 
     var sut = new MyEventRaiser(); 

     sut.MonitorEvents(); 

     sut.Process("Hello"); 

     sut.ShouldRaise("MyEvent").WithSender(sut); 
    } 

    [TestMethod] 
    public void my_event_should_not_be_raised() 
    { 
     var sut = new MyEventRaiser(); 

     sut.MonitorEvents(); 

     sut.Process(null); 

     sut.ShouldNotRaise("MyEvent"); 
    } 
} 

您需要使用下面的命名空間:

using FluentAssertions; 
using FluentAssertions.EventMonitoring; 
+0

感謝,FluentAssertions很酷 –

相關問題