我有一个单元测试,它故意生成一个未处理的异常。我已经为未处理的异常连接了一个处理程序(我想测试它),使用:
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 w/ vs2010。
发布于 2011-02-16 20:19:15
您测试的不是处理程序,而是处理程序应该执行操作的条件。Concider将Exceptionhandler提取到自己的类中,如下所示:
internal class AnExceptionHandler
{
public static void UnhandledHandler(object sender, UnhandledExceptionEventArgs args)
{
//Do your thing and test this.
}
}实例化这个类,并将事件挂接到这里。
希望这能有所帮助。
向您致敬,莫腾
https://stackoverflow.com/questions/5006929
复制相似问题