2010-08-20 64 views
3

我正在測試啓動輔助線程的代碼。而這個線程有時會拋出一個異常。如果該例外處理不當,我想編寫一個測試失敗。NUnit輔助線程異常

我已準備了考驗,我所看到的在NUnit的是:

LegacyImportWrapperTests.Import_ExceptionInImport_Ok : PassedSystem.ArgumentException: aaaaaaaaaa 
at Import.Legacy.Tests.Stub.ImportStub.Import() in ImportStub.cs: line 51... 

但測試被標記爲綠色。所以,NUnit知道這個例外,但爲什麼它將測試標記爲通過?

回答

4

,你可以看到在輸出異常的詳細信息並不一定意味着NUnit的是注意到該異常。

我已經使用在AppDomain.UnhandledException事件來監視這樣的情景測試(考慮到例外是未處理的,我以爲是這裏的情況):如果你只想測試特定的例外

bool exceptionWasThrown = false; 
UnhandledExceptionEventHandler unhandledExceptionHandler = (s, e) => 
{ 
    if (!exceptionWasThrown) 
    { 
     exceptionWasThrown = true; 
    } 
}; 

AppDomain.CurrentDomain.UnhandledException += unhandledExceptionHandler; 

// perform the test here, using whatever synchronization mechanisms needed 
// to wait for threads to finish 

// ...and detach the event handler 
AppDomain.CurrentDomain.UnhandledException -= unhandledExceptionHandler; 

// make assertions 
Assert.IsFalse(exceptionWasThrown, "There was at least one unhandled exception"); 

你可以做的是,在事件處理程序:

UnhandledExceptionEventHandler unhandledExceptionHandler = (s, e) => 
{ 
    if (!exceptionWasThrown) 
    { 
     exceptionWasThrown = e.ExceptionObject.GetType() == 
           typeof(PassedSystem.ArgumentException); 
    } 
};