2011-02-15 112 views
0

我有一个故意生成未处理的异常的单元测试。使用NUnit测试未处理的异常处理程序

AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler; 

我的测试情况如下:

LogClient client = new LogClient();  // The handler is wired up in here 

Trace.TraceInformation("About to cause an unhandled divide-by-zero exception."); 

for (int i = 10; i > -10; --i) 
{ 
    int j = 100/i; 
    Console.WriteLine("i={0}, j={1}", i, j); 
} 

Assert.NotNull(client.UnhandledException); 

当然,抛出异常和NUnit我已经使用有线了未处理异常(我想测试它)的处理程序捕获它并且未通过测试。我试着加入

[ExpectedException(typeof(DivideByZeroException))] 

和测试“通过”,但我的处理程序,不会被调用永远不会执行的Assert.NotNull。我想知道是否有可能为未处理的异常处理程序编写单元测试。任何指针赞赏。

我使用NUnit的2.5.7瓦特/ VS 2010

+0

[这个问题](http://stackoverflow.com/questions/3529917/nunit-secondary-thread-exception)表明,它能够建立一个`UnhandledExceptionHandler`使用Nunit;你确定它正在`LogClient`构造函数中设置吗?尝试在测试中明确设置处理程序。 – 2011-02-15 17:18:00

回答

0

你是不是测试的处理程序,但条件中的处理程序应该采取行动。 Concider将异常处理程序提取到它自己的类中,如:

internal class AnExceptionHandler 
    { 
     public static void UnhandledHandler(object sender, UnhandledExceptionEventArgs args) 
     { 
      //Do your thing and test this. 
     } 
    } 

实例化此类,然后连接到此事件。

希望这会有所帮助。

问候, 的Morten