{ martowen.com }

Verifying ILogger<T> invocations with Moq

Mar 15, 2023
1 minute

I don’t like to use .Verify too much in Moq, but recently I have found it useful to be able to verify something has happened by checking an invocation on an ILogger<T>. To achieve this I use the following utility method:

public static void VerifyLogMessage<T>(Mock<ILogger<T>> mockLogger, LogLevel logLevel, string message)
{
mockLogger.Verify(l => l.Log(
It.Is<LogLevel>(ll => ll == logLevel),
It.Is<EventId>(eventId => eventId.Id == 0),
It.Is<It.IsAnyType>((@object, @type) =>
@object.ToString() ==
message &&
@type.Name == "FormattedLogValues"),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception, string>>()), Times.Once);
}

And an example usage of it would be:

VerifyLogMessage(_mockLogger, LogLevel.Information, "Cancelling Consumer 'FakeConsumer'");