I'm trying to unit test some usages of LoggerMessage.Define() using the Moq library in xUnit but can't figure it out. The below is an example of a logging function I've created and below that is a sample unit test that failed to check it was called.
LoggerMessage.Define() example:
public static class GlobalExceptionLoggerMessage
{
public static Action<ILogger, string, Exception> GlobalException = LoggerMessage.Define<string>(
LogLevel.Error,
new EventId(StatusCodes.Status500InternalServerError, nameof(GlobalException)),
"{Message}");
public static void LogGlobalException(this ILogger logger, string message, Exception exception)
{
GlobalException(logger, message, exception);
}
}
Unit test example I tried:
[Fact]
public void LogGlobalExceptionLogTest()
{
var loggerMock = new Mock<ILogger<object>>();
var exception = new Exception("Person must exist.");
const string message = "Person must exist for an object.";
loggerMock.Object.LogGlobalException(message, exception);
loggerMock.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)));
}
Can someone please shine some light on how I might fix this?
Thanks!