C# 单元测试中未启用 ILogger.LogLevel
我有一个 Microsoft.Extensions.Logging.ILogger 的扩展方法,它检查给定的日志级别是否启用。然后继续进行实际的日志记录。 当我尝试对该方法进行单元测试时,我发现 logger.IsEnabled(logLevel) 对于单元测试项目中的所有日志级别始终返回 false,导致我的测试失败。
如果我删除此 isEnabled 检查,那么我的单元测试就会通过。
尽管如此,实际项目和单元测试项目中的 appsettings.json 文件中设置了默认日志级别。
我的扩展方法的代码是:
public static class LoggerExtensions
{
public static void LogErrorExt(this ILogger logger, string? message, params object?[] args)
{
if (logger.IsEnabled(LogLevel.Error))
{
logger.LogError(message, args);
}
}
}
我的单元测试类的代码是这样的:
[TestClass]
public class ImprovedExtensionsTests
{
private readonly Mock < ILogger > _logger;
public ImprovedExtensionsTests()
{
_logger = new Mock < ILogger > ();
}
[TestMethod]
public void TestOne()
{
_logger.Object.LogErrorExt("Testing ", 12);
_logger.Verify(x => x.Log(
LogLevel.Error,
It.IsAny < EventId > (),
It.IsAny < It.IsAnyType > (),
It.IsAny < Exception > (),
(Func < It.IsAnyType, Exception, string > ) It.IsAny < object > ()), Times.Once);
}
}
如何在单元测试项目中设置日志级别并在运行测试时启用它们?
I have an extension method for Microsoft.Extensions.Logging.ILogger which checks if the given log level is enabled or not. And then proceeds with the actual logging.
When I try to unit test this method, I see that logger.IsEnabled(logLevel) always returns false for all the log levels in the unit test project, causing my tests to fail.
If I remove this isEnabled check, then my unit test passes.
Even though, a default log level is set in the appsettings.json file in the actual project as well as unit test project.
The code for my extension method is:
public static class LoggerExtensions
{
public static void LogErrorExt(this ILogger logger, string? message, params object?[] args)
{
if (logger.IsEnabled(LogLevel.Error))
{
logger.LogError(message, args);
}
}
}
The code for my unit test class is this:
[TestClass]
public class ImprovedExtensionsTests
{
private readonly Mock < ILogger > _logger;
public ImprovedExtensionsTests()
{
_logger = new Mock < ILogger > ();
}
[TestMethod]
public void TestOne()
{
_logger.Object.LogErrorExt("Testing ", 12);
_logger.Verify(x => x.Log(
LogLevel.Error,
It.IsAny < EventId > (),
It.IsAny < It.IsAnyType > (),
It.IsAny < Exception > (),
(Func < It.IsAnyType, Exception, string > ) It.IsAny < object > ()), Times.Once);
}
}
How can I set the log levels in unit test project and make them enabled while running the tests?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须为 ILogger 模拟创建必要的设置,例如:
在调用
LogErrorExt
之前(例如,直接在_logger = new Mock();
之后)。You have to create the necessary setup for your ILogger mock, e.g.:
before the call to
LogErrorExt
(e.g. directly after_logger = new Mock<ILogger>();
).