NUnit 辅助线程异常 [英] NUnit secondary thread exception

查看:57
本文介绍了NUnit 辅助线程异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm testing the code which starts a secondary thread. And this thread sometimes throws an exception. I'd like to write a test which fails if that exception isn't handled properly.

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

I've prepared that test, and what I'm seeing in NUnit is:

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

但是测试被标记为绿色.那么,NUnit 知道该异常,但为什么它将测试标记为通过?

But the test is marked as GREEN. So, NUnit knows about that exception, but why does it mark the test as Passed?

推荐答案

您可以在输出中看到异常详细信息并不一定意味着 NUnit 知道异常.

That you can see the exception details in the output does not necessarily mean that NUnit is aware of the exception.

我使用了 AppDomain.UnhandledException 事件以在测试期间监视此类场景(假设未处理异常,我认为此处就是这种情况):

I have used the AppDomain.UnhandledException event to monitor scenarios like this during testing (given that the exception is unhandled, which I assume is the case here):

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");

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

If you want to test only for specific exceptions you can do that in the event handler:

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

这篇关于NUnit 辅助线程异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆