MS UnitTestFramework检索和记录异常C#

我刚开始使用MS的UnitTestFramework进行一个相当广泛的自动化项目.我注意到的一件事是,当我的代码中有错误-不是我测试的应用程序-框架捕获了该错误并以一种很高兴的方式使测试失败,该错误使测试迭代得以完成.但是,我希望能够看到这些例外情况和我的log4net日志中有堆栈跟踪信息,到目前为止,我还没有办法在我的测试清理中(或在try catch块之外的任何地方,我无意在每种方法中泼洒)抓取它们.

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

解决方法:

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

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#-log4net应该如何在应用程序内正确设置“ EventLogAppender”的“源”?


下一篇:首页> C#> log4net AdoNetAppender在数据库中插入“ Null”字符串,而不是null