AppDomain.UnhandledException处理程序不会在unit testing中触发
在下面的代码片段中,为什么在unit testing中抛出exception时,附加的处理程序( 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。 我只想找出原因,在unit testing中,处理程序不会触发。
exception将渗透调用堆栈,直到您到达可以处理该exception,AppDomain边界或堆栈顶部(按优先级顺序)的try / catch块。
如果您在NUnit提供的相同AppDomain中执行,NUnit将捕获您的exception。 这会抢占AppDomain边界内容,这可能会调用您的事件。
因此,您的测试需要创建一个新的AppDomain并在那里执行其代码(包括设置,它为AppDomain.UnhandledException添加事件处理程序)。 一切都应该按预期工作。
我猜,事件没有被触发,因为处理了exception。 通过测试框架,生成报告。
据我所知,未处理的exception事件仅在默认的AppDomain中触发。 我认为NUnit使用不同的AppDomain来执行测试,这就是你的事件没有被触发的原因。