2010-08-20 65 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); 
    } 
};