【问题标题】:NUnit secondary thread exceptionNUnit 辅助线程异常
【发布时间】:2010-08-20 10:10:08
【问题描述】:

我正在测试启动辅助线程的代码。而且这个线程有时会抛出异常。我想编写一个测试,如果没有正确处理该异常,该测试将失败。

我已经准备好了测试,我在 NUnit 中看到的是:

LegacyImportWrapperTests.Import_ExceptionInImport_Ok : PassedSystem.ArgumentException: aaaaaaaaaa
at Import.Legacy.Tests.Stub.ImportStub.Import() in ImportStub.cs: line 51...

但是测试被标记为绿色。那么,NUnit 知道该异常,但为什么它会将测试标记为通过?

【问题讨论】:

    标签: c# multithreading nunit


    【解决方案1】:

    您可以在输出中看到异常详细信息并不一定意味着 NUnit 知道该异常。

    我在测试期间使用了AppDomain.UnhandledException 事件来监控这样的场景(假设异常未处理,我假设这里就是这种情况):

    bool exceptionWasThrown = false;
    UnhandledExceptionEventHandler unhandledExceptionHandler = (s, e) =>
    {
        if (!exceptionWasThrown)
        {
            exceptionWasThrown = true;
        }
    };
    
    AppDomain.CurrentDomain.UnhandledException += unhandledExceptionHandler;
    
    // perform the test here, using whatever synchronization mechanisms needed
    // to wait for threads to finish
    
    // ...and detach the event handler
    AppDomain.CurrentDomain.UnhandledException -= unhandledExceptionHandler;
    
    // make assertions
    Assert.IsFalse(exceptionWasThrown, "There was at least one unhandled exception");
    

    如果您只想测试特定异常,您可以在事件处理程序中执行此操作:

    UnhandledExceptionEventHandler unhandledExceptionHandler = (s, e) =>
    {
        if (!exceptionWasThrown)
        {
            exceptionWasThrown = e.ExceptionObject.GetType() == 
                                     typeof(PassedSystem.ArgumentException);
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-09
      • 2019-08-24
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多