为什么 log4net XmlConfigurator 属性不适用于我的单元测试

Why doesn't the log4net XmlConfigurator attribute work for my unit tests

我正在使用 log4net,试图在我的单元测试中登录。如果我手动调用

log4net.Config.XmlConfigurator.Configure();

因为它有效,所以似乎消除了所有 "bad config, config location" 问题。

可以,但是有大量的测试类,这样不好。

我加了

[assembly: log4net.Config.XmlConfigurator(Watch=true)]

到我的测试项目的 assemblyinfo,但是当我 运行(通过本机 MSTest 或 Resharper 测试 运行ner)时,我没有记录。

帮忙?

正如 documentation for assembly attributes

中所说

Therefore if you use configuration attributes you must invoke log4net to allow it to read the attributes. A simple call to LogManager.GetLogger will cause the attributes on the calling assembly to be read and processed. Therefore it is imperative to make a logging call as early as possible during the application start-up, and certainly before any external assemblies have been loaded and invoked.

由于单元测试运行器加载测试程序集以查找和测试,因此无法在单元测试项目中使用程序集属性初始化 log4net,您将不得不使用 XmlConfigurator.

编辑:as linked in a comment by OP this can be done in one place for the whole test project by using the AssemblyInitializeAttribute

Source

[AssemblyInitialize()]
public static void MyTestInitialize(TestContext testContext)
{
// Take care the log4net.config file is added to the deployment files of the testconfig
FileInfo fileInfo;
string fullPath = Path.Combine(System.Environment.CurrentDirectory, "log4net.config");
fileInfo = new FileInfo(fullPath);