Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you unit test LoggerMessage.Define() in .NET Core 3.1 with Moq?

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!

like image 584
Benjamin Avatar asked Oct 26 '25 06:10

Benjamin


1 Answers

You need to do some additional set up. If you take a look inside the static Define method you'll see the following:

if (!logger.IsEnabled(logLevel))
  return;
Log(logger, arg1, exception);

You've not set up IsEnabled on your mocked logger, so it'll return a default bool (false) and won't invoke the Log method.

Taking your sample, if you add the following:

loggerMock.Setup(x => x.IsEnabled(It.IsAny<LogLevel>())).Returns(true);

...your verify statement starts working.

Working example

like image 60
rgvlee Avatar answered Oct 28 '25 20:10

rgvlee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!