【问题标题】:MS UnitTestFramework retrieve and log exceptions c#MS UnitTestFramework 检索和记录异常 c#
【发布时间】:2018-12-13 08:16:53
【问题描述】:

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

有人知道如何将这些异常记录到我的日志中吗?

【问题讨论】:

    标签: c# log4net microsoft-test-manager vs-unit-testing-framework


    【解决方案1】:

    您可以通过AppDomain.FirstChanceException Event 使用First-Chance Exception Notifications -

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

    这样的事情(注意它在a method marked as AssemblyInitialize, which means it runs once per test run中,并且代码不包括测试失败时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);
             };
        }
    }
    

    【讨论】:

    • 我希望我能给你超过 1 票,这让我发疯了。对于使用此解决方案的其他任何人,我将其放入 if 以过滤掉噪音,因为我真的只需要内部异常: e.Exception.InnerException != null
    【解决方案2】:

    如果您可以替换 [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");
    }
    

    当测试并行执行时,该方法也适用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多