【问题标题】:AppDomain.UnhandledException handler doesn't fire in unit testAppDomain.UnhandledException 处理程序不会在单元测试中触发
【发布时间】:2012-02-06 09:26:45
【问题描述】:

在下面的代码 sn-p 中,为什么在单元测试中抛出异常时,附加的处理程序(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");
    }

}

输出:(没有问题)

------ 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 将不是您正在测试的应用程序,而是应用程序测试人员......如果您想测试异常谷歌 NUnit 预期异常。
  • 首先我试图测试 CurrentDomain_UnhandledException 是否正常工作,但因为它从未在我的测试运行中执行过;我只是想知道为什么没有。我的目的不是测试一个方法是否抛出异常。
  • 启动另一个线程,这样 NUnit 就无法捕捉到异常。
  • 你为什么要测试.net?如果你有很多空闲时间,我可以帮你找点事情做。 :)
  • @HansPassant 谢谢,这行得通!所以 NUnit 只是在 try-catch 块中执行测试,并且在它自己的 AppDomain 中没有 unhandled_exception_handler。请将此作为答案发布,我会接受。

标签: c# testing exception-handling nunit


【解决方案1】:

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

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

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

【讨论】:

  • 我接受这个答案,因为它是最详细的答案。创建一个线程也避开了 Hans Passant 建议的 NUnit 的 catch 子句。
【解决方案2】:

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

【讨论】:

  • 可能,但是如果框架处理它以生成报告,为什么我在输出中看不到它?
  • @henginy,你在说什么?您确实在输出中看到它——它就在您粘贴在问题中的输出中:Test 'xxxxx.Test.MyTests.ExceptionTest1' failed: System.Exception : ExceptionInTest
  • 哦,对不起。我正忙于查看未处理的异常处理程序的输出,以至于我错过了它。感谢您指出。
【解决方案3】:

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

【讨论】:

  • 我在同一条轨道上,NUnit 确实使用不同的 AppDomain (nunit.org/index.php?p=assemblyIsolation&r=2.5.7)。然而,MSDN 说“这个事件可以在任何应用程序域中处理”(msdn.microsoft.com/en-us/library/…),所以这是我的想法:我本可以从我的默认应用程序域中捕获这个异常,但我不能,所以 NUnit 必须有一个 UnhandledException 处理程序在自己的 AppDomain 中。
  • 但是有一个问题,我在测试本身中注册了处理程序。所以应该在NUnit的AppDomain中注册..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-07
相关资源
最近更新 更多