gpt4 book ai didi

c# - MS UnitTestFramework 检索和记录异常 c#

转载 作者:行者123 更新时间:2023-11-30 15:22:53 25 4
gpt4 key购买 nike

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

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

最佳答案

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

This event is only a notification. Handling this event does not handle the exception or affect subsequent exception handling in any way. After the event has been raised and event handlers have been invoked, the common language runtime (CLR) begins to search for a handler for the exception. FirstChanceException provides the application domain with a first chance to examine any managed exception.

所以是这样的(注意它在 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);
};
}
}

关于c# - MS UnitTestFramework 检索和记录异常 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35016591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com