NUnit secondary thread exception

杀马特。学长 韩版系。学妹 提交于 2019-12-10 16:19:25

问题


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.

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...

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


回答1:


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

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


来源:https://stackoverflow.com/questions/3529917/nunit-secondary-thread-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!