C# – How to Moq Mock a LoggerFactory in C# AspNet Core

cmoqunit testing

I am trying to write some unit tests for controller actions. To do that, I am using XUnit and Moq. The controllers have an ILoggerFactory injected in the constructor. How does one Moq this up for testing?

I have tried mocking a Logger for the controller class, and then mocking up CreateLogger to return the mock Logger, but I keep getting various test runtime NullReferenceExceptions when the LogInformation() function is called.

        //   Logger that yields only disappointment...          
        var mockLogger = new Mock<ILogger<JwtController>>();
        mockLogger.Setup(ml => ml.Log(It.IsAny<LogLevel>(), It.IsAny<EventId>(), It.IsAny<object>(), It.IsAny<Exception>(), It.IsAny<Func<object, Exception, string>>()));
        var mockLoggerFactory = new Mock<ILoggerFactory>();
        mockLoggerFactory.Setup(mlf => mlf.CreateLogger("JwtController")).Returns(mockLogger.Object);

I assume the problem is that LogInformation is being called, and this is an extension method, so how to moq that?

Best Answer

For what it's worth: instead of mocking an ILoggerFactory, you could also pass an instance of NullLoggerFactory. This NullLoggerFactory will return instances of NullLogger. According to the docs, this is a:

Minimalistic logger that does nothing.