Implementing an unhandled exception handler in C # Unit Tests

I have several tests and they rely heavily on some generic code that I cannot change. This generic code sometimes throws an exception and I want to be able to handle all uncaught instances of that exception without wrapping every call of the generic code in a try catch (there are a lot of tests here).

I also want to be able to re-throw exceptions that are not of the type I am looking for.

I tried

public void init() 
{
    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    Logger.Info("Caught exception");
    throw (Exception)e.ExceptionObject;
}

      

But it looks like the unit test ( Microsoft.VisualStudio.QualityTools.UnitTestsFramework

) framework is doing something with AppDomain

and won't let me replace its handler UnhandledException

, or I just don't understand how the unit test framework is handled AppDomain

(very likely).

Anyone have any suggestions?

+3


source to share


1 answer


Try connecting to the event AppDomain.CurrentDomain.FirstChanceException

. In the Microsoft documentation:

Thrown when an exception is thrown in managed code, searches the call stack for the exception handler in the application domain before runtime.



In other words, you can catch it in front of the Unit Test Framework. More details here .

0


source







All Articles