[英]Mock the logger of NLog and read logged message
我使用 NLog 4.5.11 進行日志記錄,使用 moq 4.10.1 進行 mocking。
我有一個中間件,它使用 NLog 將異常詳細信息寫入日志文件。
我需要在我的 API 項目中對中間件進行單元測試,並檢查記錄的消息以獲得正確的值。
這就是我聲明異常記錄器的方式:
private static Logger _exceptionLogger = LogManager.GetLogger("ExceptionLogger");
這就是我在中間件構造函數中初始化 Logmanager 的方式:
LogManager.LoadConfiguration(String.Concat(Directory.GetCurrentDirectory(), "/nlog.config"));
這就是我記錄異常消息的方式:
_exceptionLogger.Error(exceptionMessage);
有什么方法可以做到這一點,而無需實際在文件中寫入和讀取記錄的消息?
建議在單元測試中使用Memory 目標,而不是 mocking 記錄器。
例如:
// 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 / 方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.