开发者

Unit Testing an Unhandled Exception Handler with NUnit

开发者 https://www.devze.com 2023-02-10 11:19 出处:网络
I have a unit test that deliberately generates an unhandled exception. I\'ve wired up a ha开发者_运维百科ndler for unhandled exceptions (which I\'d like to test) using:

I have a unit test that deliberately generates an unhandled exception. I've wired up a ha开发者_运维百科ndler for unhandled exceptions (which I'd like to test) using:

AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;

My test is as follows:

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

Of course, the exception is thrown and NUnit catches it and fails the test. I've tried adding the

[ExpectedException(typeof(DivideByZeroException))]

and the test "passes" but my handler is never called and the Assert.NotNull is never executed. I'm wondering if it is possible to write a unit test for an unhandled exception handler. Any pointers appreciated.

I'm using NUnit 2.5.7 w/ VS 2010.


You are not testing the handler, but the condition in which the handler should act. Concider extracting the Exceptionhandler into its own class like:

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

Instantiate this class, and hook up the event up to this.

Hope this helps.

Regards, Morten

0

精彩评论

暂无评论...
验证码 换一张
取 消