Aspnetcore: How to test asp.net core built-in Ilogger

Created on 21 Sep 2016  路  2Comments  路  Source: dotnet/aspnetcore

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 _logger;

public InvoiceApi(ILogger<InvoiceApi> logger)
{
    _logger = logger;
}

then I use it like: _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);

then tried verify:

MockLogger.Verify(m => m.LogError(It.Is<string>(s => s.Contains("CreateInvoiceFailed"))));

but it throw:

Invalid verify on a non-virtual (overridable in VB) member: m => m.LogError

So, how can I verify this logs logged?

I asked this in SO and the answer I got was that I need to wrap the ILogger in my own interface.

But I was sure that the main objective of ILogger is to be the wrapper for logs, so is not it'll be better to do it testable?

thanks

Most helpful comment

Extension methods strike again!

All 2 comments

LogError is an extension method on ILogger. ILogger.Log is the method you want to mock.

Extension methods strike again!

Was this page helpful?
0 / 5 - 0 ratings