NUnit次要线程异常

4

我正在测试启动辅助线程的代码。有时候这个线程会抛出异常。我想编写一个测试,如果该异常没有得到适当处理,则测试失败。

我已经准备好了测试,在 NUnit 中看到的结果是:

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

但测试被标记为绿色。因此,NUnit知道该异常,但为什么它将测试标记为已通过?
1个回答

5
你可以在输出中看到异常详细信息,并不一定意味着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);
    }
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接