Mocking ILogger

Mocking extension methods is not possible as they are static.

Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object.

Work around

Create the mocked logger that is injected into SomeServiceClient

1
var loggerMock = new Mock<ILogger<SomeServiceClient>>();

After injecting loggerMock.Object and calling the unit of work you can verify what the extension method is calling under the hood.

Key things to look at here are:

  • LogLevel below is LogLevel.Error which will be for _logger.LogError from Microsoft.Extensions.Logging
  • logEntryToBeWritten is the text to be logged without the exeption.
var logEntryToBeWritten = "The what what borked";

loggerMock.Verify(
    x => x.Log(
        It.Is<LogLevel>(l => l == LogLevel.Error),
        It.IsAny<EventId>(),
        It.Is<It.IsAnyType>((v, t) => v.ToString() == logEntryToBeWritten),
        It.IsAny<Exception>(),
        It.Is<Func<It.IsAnyType, Exception, string>>((v, t) => true)));

References