【发布时间】: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