title: Testing Last Chance Exception Handling
body: <p>I am trying to write a unit test to cover code found in our "last chance exception handler".</p>
  
  <p>When referring to last chance exception handling I am talking about event handlers of the events:</p>
  
  <p>Application.ThreadException
  AppDomain.CurrentDomain.UnhandledException</p>
  
  <p>More or less I am verifying that logs are being produced detailing the information produced by the exception. My test is similar to:</p>
  
  <pre><code> [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");
  }
  </code></pre>
  
  <p>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.  </p>
  
  <p>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. </p>
  
  <p>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?</p>
  
  <p>I'm using NUnit 2.4 and running it in the IDE using ReSharper.</p>