对带log4net日志输出的类库,C#单元测试异常,log4net初始化异常。

问题遇到的现象和发生背景

用一个窗体程序调用类库,可以正常输出,但是用c#的单元测试来调用类库就出错。

问题相关代码,请勿粘贴截图

using Microsoft.VisualStudio.TestTools.UnitTesting;

using MyBase;

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]
namespace TestProject1
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{

        log4net.Config.XmlConfigurator.Configure(); // log4net

        Class1 c = new Class1();
        c.TestLog();
    }
}

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyBase
{
public class Class1
{
public void TestLog()
{
LogHelper.WriteSysLog("Class1.TestLog()");
}
}
}

运行结果及报错内容

代码:log4net.Config.XmlConfigurator.Configure(); 执行异常,信息如下:

System.TypeInitializationException
HResult=0x80131534
Message=The type initializer for 'log4net.Core.LoggerManager' threw an exception.
Source=log4net
StackTrace:
at log4net.Core.LoggerManager.GetRepository(Assembly repositoryAssembly)
at log4net.LogManager.GetRepository(Assembly repositoryAssembly)
at log4net.Config.XmlConfigurator.Configure()
at TestProject1.UnitTest1.TestMethod1() in C:...TestProject1\UnitTest1.cs:line 16

内部异常 1:
TypeInitializationException: The type initializer for 'log4net.Util.SystemInfo' threw an exception.

内部异常 2:
FileNotFoundException: Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. 系统找不到指定的文件。

我的解答思路和尝试过的方法

1、检查过,测试程序的同级目录有log4net.config文件;
2、原来用FORM程序,调用类库可以正常输出日志。

我想要达到的结果

希望能够单元测试带有log4net的类库。

.net core吗?试试用Nuget 安装System.Configuration.ConfigurationManager,原来的form没问题,应该用的framework
参考


Configuration manager assembly not loading in class library file https://social.msdn.microsoft.com/Forums/en-US/3be6809d-96a2-4679-9aa9-b7899834b34d/configuration-manager-assembly-not-loading-in-class-library-file?forum=aspmvc

c# - Can't use System.Configuration.Configuration manager in a .NET Standard2.0 library on .NET FX4.6 - Stack Overflow https://stackoverflow.com/questions/46360716/cant-use-system-configuration-configuration-manager-in-a-net-standard2-0-libra

进一步发现,在单元测试类中, System.Configuration下只有 System.Configuration.Assemblies,正常的话在其他地方下面有很多子项。

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632