views:

12

answers:

1

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  A: 

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);
    }
};
Fredrik Mörk