2011-02-15 109 views
0

我有一個故意生成未處理的異常的單元測試。使用NUnit測試未處理的異常處理程序

AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler; 

我的測試情況如下:

LogClient client = new LogClient();  // The handler is wired up in here 

Trace.TraceInformation("About to cause an unhandled divide-by-zero exception."); 

for (int i = 10; i > -10; --i) 
{ 
    int j = 100/i; 
    Console.WriteLine("i={0}, j={1}", i, j); 
} 

Assert.NotNull(client.UnhandledException); 

當然,拋出異常和NUnit我已經使用有線了未處理異常(我想測試它)的處理程序捕獲它並且未通過測試。我試着加入

[ExpectedException(typeof(DivideByZeroException))] 

和測試「通過」,但我的處理程序,不會被調用永遠不會執行的Assert.NotNull。我想知道是否有可能爲未處理的異常處理程序編寫單元測試。任何指針讚賞。

我使用NUnit的2.5.7瓦特/ VS 2010

+0

[這個問題](http://stackoverflow.com/questions/3529917/nunit-secondary-thread-exception)表明,它能夠建立一個`UnhandledExceptionHandler`使用Nunit;你確定它正在`LogClient`構造函數中設置嗎?嘗試在測試中明確設置處理程序。 – 2011-02-15 17:18:00

回答

0

你是不是測試的處理程序,但條件中的處理程序應該採取行動。 Concider將異常處理程序提取到它自己的類中,如:

internal class AnExceptionHandler 
    { 
     public static void UnhandledHandler(object sender, UnhandledExceptionEventArgs args) 
     { 
      //Do your thing and test this. 
     } 
    } 

實例化此類,然後連接到此事件。

希望這會有所幫助。

問候, 的Morten