NUnit次要线程异常

Sha*_*dix 4 c# multithreading nunit

我正在测试启动辅助线程的代码.而这个线程有时会引发异常.如果没有正确处理该异常,我想编写一个失败的测试.

我准备了那个测试,我在NUnit中看到的是:

LegacyImportWrapperTests.Import_ExceptionInImport_Ok : PassedSystem.ArgumentException: aaaaaaaaaa
at Import.Legacy.Tests.Stub.ImportStub.Import() in ImportStub.cs: line 51...
Run Code Online (Sandbox Code Playgroud)

但测试标记为绿色.所以,NUnit知道这个异常,但为什么它将测试标记为Passed?

Fre*_*örk 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");
Run Code Online (Sandbox Code Playgroud)

如果您只想测试特定的异常,可以在事件处理程序中执行此操作:

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