【发布时间】:2020-10-06 06:04:00
【问题描述】:
在我的 C# 应用程序中,我有一个 getLogFile,它是通过调用 GetLogFile() 方法设置的:
private static string getLogFile = GetLogFile();
private static string GetLogFile()
{
var fileTarget = (FileTarget)LogManager.Configuration.FindTargetByName("file-target");
var logEventInfo = new LogEventInfo();
string fileName = fileTarget.FileName.Render(logEventInfo);
if (!File.Exists(fileName))
throw new Exception("Log file does not exist.");
return fileName;
}
我现在正在尝试对一些需要设置 getLogFile 变量的代码进行单元测试。我想以某种方式模拟它,因为我想使用特定的日志数据进行测试,但不知道如何去做。我该怎么做?
【问题讨论】:
-
不要尝试模拟私有字段,而是使用 .NET Core 的日志记录(或任何其他日志记录库,如 Serilog、NLog)并模拟
ILogger接口或添加测试接收器而不是实际接收器 -
顺便说一句,无论如何你都必须使用
ILogger- 所有需要日志记录的 .NET Core 包都希望它存在 -
这能回答你的问题吗? Is it possible to mock NLog log methods?
标签: c# asp.net unit-testing .net-core nlog