问题
In the code snippet below, why wouldn't the attached handler (of AppDomain.CurrentDomain.UnhandledException
event) fire up when an exception is thrown in the unit test?
I'm 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 gotchas)
------ 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 .Net framework or NUnit. I just want to find out the reason why, in a unit test, the handler wouldn't fire.
回答1:
An exception will percolate up the call stack until you reach a try/catch block that can handle that exception, an AppDomain boundary, or the top of the stack (in that order of priorities).
If you're executing within the same AppDomain that NUnit gives you, NUnit will catch your exception. This preempts the AppDomain boundary stuff, which would have called your event.
So your test needs to create a new AppDomain and execute its code there (including the setup, which adds the event handler for AppDomain.UnhandledException). Everything should work as expected there.
回答2:
I guess, the event isn't fired because exception is handled. By test framework, to generate report.
回答3:
As far as I know the unhandled exception event is only triggered in the default AppDomain. I think NUnit uses to execute the tests a different AppDomain which is the reason why your event does not get triggered.
来源:https://stackoverflow.com/questions/9157991/appdomain-unhandledexception-handler-doesnt-fire-in-unit-test