在C#单元测试中实现未处理的异常处理程序

我有一些测试,他们严重依赖一些我无法修改的共享代码.这个共享代码有时会引发异常,我希望能够处理这个异常的所有未捕获实例,而不必在try catch中包含对共享代码的每次调用(这里有多年的测试).

我还希望能够重新抛出那些不是我正在寻找的类型的异常.

我试过了

public void init() 
{
    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    Logger.Info("Caught exception");
    throw (Exception)e.ExceptionObject;
}

但看起来股票单元测试框架(Microsoft.VisualStudio.QualityTools.UnitTestsFramework)正在对AppDomain做一些事情并阻止我替换它的UnhandledException处理程序,或者我根本不理解单元测试框架如何处理AppDomains(极有可能) .

有人有什么建议吗?

最佳答案 尝试附加到AppDomain.CurrentDomain.FirstChanceException事件.根据Microsoft的文档:

Occurs when an exception is thrown in managed code, before the runtime
searches the call stack for an exception handler in the application
domain.

换句话说,您可以在单元测试框架之前捕获它.更多信息here.

点赞