views:

285

answers:

2

I am trying to write a unit test to cover code found in our "last chance exception handler".

When referring to last chance exception handling I am talking about event handlers of the events:

Application.ThreadException AppDomain.CurrentDomain.UnhandledException

More or less I am verifying that logs are being produced detailing the information produced by the exception. My test is similar to:

 [Test]
 public void TestMethod() 
 {
    //Setup log4net ConsoleAppender here
    //hooking a MemoryStream to the Console.SetOut done here

    ExceptionHandler.InstallExceptionHandler();
    Thread exceptionThread = new Thread(ThrowException);
    Thread.Start();

    //read stream here

    Assert.That(streamContainsExceptionText);
 }

private void ThrowException() {
 throw new Exception("Unhandled Exception");
}

The Exception Handler is a singleton that when "Installed" just adds handlers to the previously given events. The strange thing is that I don't have consistent results. Breaking and debugging doesn't seem to be an option because it seems to get in between the exception and the ExceptionHandler.

I place several "Console.WriteLine()" statements throughout the code to verify where the code was failing but this is not consistent. I believe it has something to do with either the test frameworking killing the thread or possibly some sort of garbage collection.

Has anyone had experience testing a piece of code like this? Or do you have any insight into why I'm seeing this kind of behavior?

I'm using NUnit 2.4 and running it in the IDE using ReSharper.

+1  A: 

Is it possible that you're trying to read the value from the stream before the thread has started and then finished?

For this sort of thing we will put the stream read inside a loop (pseudocode):

while (!timed out) {
    read from stream;
    if (message is in stream) {
        set success flag;
        break;
    }
    sleep;
 }
 if (!success flag) {
     throw test failure;
 }
David Norman
+2  A: 

It is a race condition, your thread might not always have the time to do the exception + logging it.

Join the thread, so you continue after the thread finishes.

    Thread exceptionThread = new Thread(ThrowException);
    exceptionThread.Start();
    exceptionThread.Join();
    //read stream, and rest of the test

Also you might want to set a timeout on the Join call.

eglasius
Thanks, I will try this as soon as I can.
Adam Driscoll