AppDomain.UnhandledException handler doesn't fire in unit test

放肆的年华 提交于 2019-12-07 11:16:16

问题


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

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