MS UnitTestFramework 检索并记录异常 c#

本文关键字:异常 记录 UnitTestFramework 检索 MS | 更新日期: 2023-09-27 18:32:00

我刚刚开始了一个相当广泛的自动化项目,该项目使用MS的UnitTestFramework。我注意到的一件事是,当我的代码中出现错误时 - 而不是我测试的应用程序 - 框架会捕获该错误并以一种允许测试迭代完成的愉快方式使测试失败。但是,我希望能够在我的log4net日志中看到这些异常和堆栈跟踪,到目前为止,我还没有发现在我的测试清理中(或尝试捕获块之外的任何地方,我无意在每个方法中飞溅)。

有人知道如何将这些异常放入我的日志中吗?

MS UnitTestFramework 检索并记录异常 c#

您可以使用

首次机会异常通知 通过 AppDomain.FirstChanceException 事件 -

此事件只是一个通知。处理此事件不处理 异常或以任何方式影响后续异常处理。 引发事件并调用事件处理程序后, 公共语言运行库 (CLR) 开始搜索 例外。FirstChanceException提供应用程序域 第一次有机会检查任何托管异常。

所以像这样的东西(注意它在一个标记为 AssemblyInitialize 的方法中,这意味着它每次测试运行一次,并且代码排除了测试失败时 MSTest 抛出的 AssertFailedException。您可能还希望排除其他异常,否则日志中可能会有很多"噪音"。

[TestClass]
public class Initialize
{
    [AssemblyInitialize]
    public static void InitializeLogging(TestContext testContext)
    {
         AppDomain.CurrentDomain.FirstChanceException += (source, e) =>
         {
           if (e.Exception is AssertFailedException == false)
                LogManager.GetLogger("TestExceptions").Error(e.Exception);
         };
    }
}
如果可以

替换 [TestMethod] 属性,那么您可以定义自己的属性MyTestMethod,例如,通过从默认值派生,如下所示:

public class MyTestMethodAttribute : TestMethodAttribute
{
    public override TestResult[] Execute(ITestMethod testMethod)
    {
        TestResult[] testResults = base.Execute(testMethod);
        foreach (var testResult in testResults.Where(e => e.Outcome == UnitTestOutcome.Failed))
            testResult.LogOutput += $"Exception `{testResult.TestFailureException.GetType().Name}` with message `{testResult.TestFailureException.Message}`.";
        return testResults;
    }
}

然后,以下测试在 Visual Studio 的测试资源管理器的标准输出面板中生成预期的日志消息Exception TestFailedException with message Assert.Fail failed. Some exception text.

[TestClass]
public class Tests
{
    [MyTestMethod]
    public void Test()
        => Assert.Fail("Some exception text");
}

当测试并行执行时,此方法也有效。