How to test asp.net core built-in Ilogger

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)


After some upgrades to .net core 3.1 FormattedLogValues become internal. We can not access it anymore. I made a extensions method with some changes. Some sample usage for extension method:

mockLogger.VerifyLog(Times.Once);
public static void VerifyLog<T>(this Mock<ILogger<T>> mockLogger, Func<Times> times)
{
    mockLogger.Verify(x => x.Log(
        It.IsAny<LogLevel>(),
        It.IsAny<EventId>(),
        It.Is<It.IsAnyType>((v, t) => true),
        It.IsAny<Exception>(),
        It.Is<Func<It.IsAnyType, Exception, string>>((v, t) => true)), times);
}