AppDomain.UnhandledException处理程序没有';t单元内点火测试

本文关键字:单元 测试 处理 UnhandledException 程序 AppDomain | 更新日期: 2023-09-27 18:23:42

在下面的代码片段中,当单元测试中抛出异常时,为什么(AppDomain.CurrentDomain.UnhandledException事件的)附加处理程序不会启动?

我在VS2010上使用NUnit 2.5.10和TestDriven.NET 3.0。

[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");
    }
}

输出:(无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).

更新:这个问题的目的不是测试.Net框架或NUnit。我只想找出在单元测试中,处理程序不会启动的原因。

AppDomain.UnhandledException处理程序没有';t单元内点火测试

异常将渗透到调用堆栈中,直到到达可以处理该异常的try/catch块、AppDomain边界或堆栈顶部(按优先级顺序)。

如果您在NUnit提供的同一个AppDomain中执行,NUnit将捕获您的异常。这会抢占AppDomain边界的东西,它会调用您的事件。

因此,你的测试需要创建一个新的AppDomain并在那里执行它的代码(包括安装程序,它为AppDomain.UnhandledException添加了事件处理程序)。一切都应该按预期进行。

我想,事件没有被触发是因为处理了异常。通过测试框架,生成报告。

据我所知,未处理的异常事件仅在默认AppDomain中触发。我认为NUnit使用不同的AppDomain来执行测试,这就是为什么您的事件没有被触发的原因。