模拟 NLog 的记录器并读取记录的消息
Mock the logger of NLog and read logged message
我使用 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);
有没有什么方法可以在不实际写入和读取文件中记录的消息的情况下做到这一点?
建议在单元测试中使用 Memory target,而不是模拟记录器。
例如:
// 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 或创建的记录器传递给您的 class / 方法。
我使用 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);
有没有什么方法可以在不实际写入和读取文件中记录的消息的情况下做到这一点?
建议在单元测试中使用 Memory target,而不是模拟记录器。
例如:
// 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 或创建的记录器传递给您的 class / 方法。