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.

Invocations

After injecting loggerMock.Object and calling the unit of work you can verify Invocations by index

1
2
3
4
5
6
7
8
9
loggerMock
.Invocations[0]
.Arguments[0]
.Should().Be(LogLevel.Error);

loggerMock
.Invocations[0]
.Arguments[2]
.ToString().Should().Be("The what what borked");

You can also use the ILogger.Moq library and then instead do something like

1
2
3
loggerMock.VerifyLog(
i => i.LogInformation("The what what borked"),
Times.Once);

Plan B, Query Underlying Method

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