0

我有一个故意生成未处理异常的单元测试。我已经使用以下方法为未处理的异常(我想测试)连接了一个处理程序:

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永远不会被执行。我想知道是否可以为未处理的异常处理程序编写单元测试。任何指针表示赞赏。

我正在使用带有 VS 2010 的 NUnit 2.5.7。

4

1 回答 1

-1

您不是在测试处理程序,而是在测试处理程序应该执行的条件。Concider 将 Exceptionhandler 提取到它自己的类中,例如:

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

实例化此类,并将事件与此挂钩。

希望这可以帮助。

问候,莫腾

于 2011-02-16T12:19:15.263 回答