AppDomain.UnhandledException handler does not run in unit test

In the code snippet below, why not turn on the handler (from the AppDomain.CurrentDomain.UnhandledException event) when the exception is thrown in the unit test?

I am using NUnit 2.5.10 with TestDriven.NET 3.0 on VS2010.

 [TestFixture] public class MyTests { private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Console.WriteLine("Gotcha!"); } [Test] public void ExceptionTest1() { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; throw new Exception("ExceptionInTest"); } } 

Output: (no error)

 ------ Test started: Assembly: WcfQueue.Test.dll ------ Test 'xxxxx.Test.MyTests.ExceptionTest1' failed: System.Exception : ExceptionInTest ProgramTests.cs(83,0): at xxxxx.Test.MyTests.ExceptionTest1() 0 passed, 1 failed, 0 skipped, took 1.98 seconds (NUnit 2.5.5). 

Update: The purpose of this question is NOT to test the .NET or NUnit environment. I just want to find out the reason why the handler does not work in unit test.

+4
source share
3 answers

The exception will leak through the call stack until you reach the try / catch block that can handle this exception, the AppDomain border, or the top of the stack (in this order of priority).

If you are running in the same AppDomain as NUnit, NUnit will catch your exception. This protects the AppDomain app material that would trigger your event.

So, your test should create a new AppDomain and execute its code there (including a setting that adds an event handler for AppDomain.UnhandledException). Everything should work as expected.

+3
source

I think the event does not fire because an exception is being handled. Using a test environment to create a report.

+2
source

As far as I know, an unhandled exception event is fired only in AppDomain by default. I think that NUnit uses another AppDomain to run the tests, which is the reason that your event does not fire.

+2
source

Source: https://habr.com/ru/post/1394981/


All Articles