如何测试asp.net核心的内置Ilogger [英] How to test asp.net core built-in Ilogger
问题描述
我想验证一些日志记录.我正在使用asp.net核心内置的ILogger,并使用asp.net核心内置的DI注入它:
I want to verify some logs logged. I am using the asp.net core built-in ILogger, and inject it with the asp.net core built-in DI:
private readonly ILogger<InvoiceApi> _logger;
public InvoiceApi(ILogger<InvoiceApi> logger)
{
_logger = logger;
}
然后我将其用作:_logger.LogError("error));
我尝试通过以下方式照常(用最小起订量)模拟它:
I tried to mock it (with moq) as usual by:
MockLogger = new Mock<ILogger<InvoiceApi>>();
并将其注入服务以通过以下方式进行测试:
and inject this in the service for test by:
new InvoiceApi(MockLogger.Object);
然后尝试验证:
MockLogger.Verify(m => m.LogError(It.Is<string>(s => s.Contains("CreateInvoiceFailed"))));
但它抛出:
对非虚拟成员(在VB中可重写)的无效验证:m => m.LogError
Invalid verify on a non-virtual (overridable in VB) member: m => m.LogError
那么,如何验证此日志已记录?
So, how can I verify this logs logged?
推荐答案
正如@Nkosi所说,您不能模拟扩展方法.您应该模拟的是 ILogger.Log
方法,该方法
As @Nkosi've already said, you can't mock an extension method. What you should mock, is the ILogger.Log
method, which LogError
calls into. It makes the verification code a bit clunky, but it should work:
MockLogger.Verify(
m => m.Log(
LogLevel.Error,
It.IsAny<EventId>(),
It.Is<FormattedLogValues>(v => v.ToString().Contains("CreateInvoiceFailed")),
It.IsAny<Exception>(),
It.IsAny<Func<object, Exception, string>>()
)
);
(不确定是否可以编译,但是要点)
(Not sure if this compiles, but you get the gist)
这篇关于如何测试asp.net核心的内置Ilogger的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!