模拟NLog的记录器并读取记录的消息

问题描述 投票:0回答:2

我使用 NLog 4.5.11 进行日志记录,使用 moq 4.10.1 进行模拟。

我有一个中间件,它使用 NLog 将异常详细信息写入日志文件。

我需要在我的 API 项目中对中间件进行单元测试,并检查记录的消息是否有正确的值。

这就是我声明异常记录器的方式:

private static Logger _exceptionLogger = LogManager.GetLogger("ExceptionLogger");

这就是我在中间件构造函数中初始化 Logmanager 的方式:

 LogManager.LoadConfiguration(String.Concat(Directory.GetCurrentDirectory(), "/nlog.config"));

这就是我记录异常消息的方式:

_exceptionLogger.Error(exceptionMessage);

有什么方法可以做到这一点,而无需实际在文件中写入和读取记录的消息?

c# .net .net-core moq nlog
2个回答
9
投票

建议在单元测试中使用内存目标,而不是模拟记录器。

例如:

// Arrange
var config = new NLog.Config.LoggingConfiguration();
var memoryTarget = new NLog.Targets.MemoryTarget();
memoryTarget.Layout = "${message}";   // Message format
config.AddRuleForAllLevels(memoryTarget);
LogManager.Configuration = config;

// Act
// Your call

// Assert
var logEvents = target.Logs;
// E.g. contains message in logEvents

PS:请注意,在上面的示例中使用了全局 LogManager,因此您无法并行运行测试。如果您需要并行测试,请创建一个新的 LogFactory 并将 LogFactory 或创建的记录器传递给您的类/方法。


0
投票

对于任何登陆这里并寻找 NLog 3.2.x 解决方案答案的人来说都是非常相似的:

// Arrange
var config = new NLog.Config.LoggingConfiguration();
var memoryTarget = new NLog.Targets.MemoryTarget();
config.AddTarget("mem", memoryTarget);

config.LoggingRules.Add(new LoggingRule("*", LogLevel.Warn, memoryTarget));
LogManager.Configuration = config;

// Act

// Assert
var logs = memoryTarget.Logs;

希望有帮助

© www.soinside.com 2019 - 2024. All rights reserved.