我正在测试启动辅助线程的代码。并且这个线程有时会抛出异常。我想编写一个测试,如果没有正确处理该异常,该测试就会失败。
我已经准备好了该测试,我在 NUnit 中看到的是:
LegacyImportWrapperTests.Import_ExceptionInImport_Ok : PassedSystem.ArgumentException: aaaaaaaaaa
at Import.Legacy.Tests.Stub.ImportStub.Import() in ImportStub.cs: line 51...
但测试标记为绿色。那么,NUnit 知道该异常,但为什么它会将测试标记为“通过”?
您可以在输出中看到异常详细信息并不一定意味着 NUnit 知道该异常。
我已经用过AppDomain.UnhandledException http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx在测试期间监视此类场景的事件(假设异常未处理,我假设这里就是这种情况):
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);
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)