【问题标题】:Testing Last Chance Exception Handling测试最后机会异常处理
【发布时间】:2009-03-10 03:24:07
【问题描述】:

我正在尝试编写一个单元测试来覆盖在我们的“最后机会异常处理程序”中找到的代码。

当提到最后机会异常处理时,我指的是事件的事件处理程序:

Application.ThreadException AppDomain.CurrentDomain.UnhandledException

我或多或少正在验证是否正在生成日志,详细说明异常产生的信息。我的测试类似于:

 [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");
}

异常处理程序是一个单例,当“安装”时,它只是将处理程序添加到先前给定的事件中。奇怪的是,我没有一致的结果。中断和调试似乎不是一种选择,因为它似乎介于异常和 ExceptionHandler 之间。

我在整个代码中放置了几个“Console.WriteLine()”语句来验证代码失败的地方,但这并不一致。我相信这与测试框架杀死线程或可能某种垃圾收集有关。

有没有人有过测试这样一段代码的经验?或者您对我为什么会看到这种行为有任何见解吗?

我正在使用 NUnit 2.4 并使用 ReSharper 在 IDE 中运行它。

【问题讨论】:

    标签: c# unit-testing exception-handling


    【解决方案1】:

    这是一个竞争条件,您的线程可能并不总是有时间处理异常并记录它。

    加入线程,以便在线程完成后继续。

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

    您可能还想在加入呼叫时设置超时。

    【讨论】:

    • 谢谢,我会尽快尝试。
    【解决方案2】:

    您是否有可能在线程开始然后结束之前尝试从流中读取值?

    对于这种事情,我们会将读取的流放在一个循环中(伪代码):

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

    【讨论】:

      猜你喜欢
      • 2016-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-27
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多