AppDomain.UnhandledException处理不火的单元测试 [英] AppDomain.UnhandledException handler doesn't fire in unit test

查看:264
本文介绍了AppDomain.UnhandledException处理不火的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码片段,为什么不(的 AppDomain.CurrentDomain.UnhandledException 事件)附加的处理火起来时,一个异常在单元测试中被抛出?

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?

我使用NUnit的2.5.10与VS2010 TestDriven.NET 3.0。

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).



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

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.

推荐答案

这是例外,直到你达到一个try / catch块可以处理该异常,一个AppDomain边界将渗透调用堆栈或者堆栈的顶部(以优先顺序)。

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).

如果你同样的AppDomain NUnit的为您提供了内执行,NUnit的会赶上你的异常。这种抢占的AppDomain边界的东西,它会叫你的事件。

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.

所以,你的测试需要创建一个新的AppDomain并有执行其代码(包括安装,这将增加为AppDomain.UnhandledException事件处理程序)。一切都应该按预期在那里。

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.

这篇关于AppDomain.UnhandledException处理不火的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆