How do I provide ILogger<T> in my unit tests of .NET Core code?

Viewed 22161

Given a class with a constructor signature of

public Foo(ILogger<Foo> logger) {
    // ...
}

that I want to test, I need some way to provide an ILogger<Foo> in the test. It's been asked before, but the only answer then was to set up a full-blown service registry, configure logging and resolve the logger from there. This seems very overkill to me.

Is there a simple way to provide an implementation of ILogger<T> for testing purposes?

Note: it doesn't have to actually log anything - just not blow up when the subject under test tries to log something.

10 Answers

You can create an instance of ILogger<Foo> using NullLoggerFactory as the factory.

Consider the following controller:

public abstract class Foo: Controller
{
    public Foo(ILogger<Foo> logger) {
        Logger = logger;
    }

    public ILogger Logger { get; private set; }
}

A sample unit test could be:

[TestMethod]
public void FooConstructorUnitTest()
{
    // Arrange
    ILogger<FooController> logger = new Logger<FooController>(new NullLoggerFactory());

    // Act
    FooController target = new FooController(logger);

    // Assert
    Assert.AreSame(logger, target.Logger);
}

If you use generic logger (ILogger<>) in your classes those instances are generated from IServiceProvider you should register generic NullLogger<> on service provider as below. Not important what you use generic type T in ILogger<>

services.AddSingleton(typeof(ILogger<>), typeof(NullLogger<>));

You could inject ILoggerFactory instead and then create the logger

public Foo(ILoggerFactory loggerFactory) {
    logger = loggerFactory.CreateLogger<Foo>();
    // ...
}

At startup you need to add the NullLoggerFactory service of course:

services.AddSingleton<ILoggerFactory, NullLoggerFactory>()

You should use the Null Object Pattern. This has two advantages for you: 1) you can get your tests up and running quickly and they won't "blow up", and 2) anyone will be able to use your class without supplying a logger. Just use NullLogger.Instance, or NullLoggerFactory.Instance.

However, you should use a mocking framework to verify that log calls get made. Here is some sample code with Moq.

    [TestMethod]
    public void TestLogError()
    {
        var recordId = new Guid("0b88ae00-7889-414a-aa26-18f206470001");

        _logTest.ProcessWithException(recordId);

        _loggerMock.Verify
        (
            l => l.Log
            (
                //Check the severity level
                LogLevel.Error,
                //This may or may not be relevant to your scenario
                It.IsAny<EventId>(),
                //This is the magical Moq code that exposes internal log processing from the extension methods
                It.Is<It.IsAnyType>((state, t) =>
                    //This confirms that the correct log message was sent to the logger. {OriginalFormat} should match the value passed to the logger
                    //Note: messages should be retrieved from a service that will probably store the strings in a resource file
                    CheckValue(state, LogTest.ErrorMessage, "{OriginalFormat}") &&
                    //This confirms that an argument with a key of "recordId" was sent with the correct value
                    //In Application Insights, this will turn up in Custom Dimensions
                    CheckValue(state, recordId, nameof(recordId))
            ),
            //Confirm the exception type
            It.IsAny<NotImplementedException>(),
            //Accept any valid Func here. The Func is specified by the extension methods
            (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),
            //Make sure the message was logged the correct number of times
            Times.Exactly(1)
        );
    }

    private static bool CheckValue(object state, object expectedValue, string key)
    {
        var keyValuePairList = (IReadOnlyList<KeyValuePair<string, object>>)state;

        var actualValue = keyValuePairList.First(kvp => string.Compare(kvp.Key, key, StringComparison.Ordinal) == 0).Value;

        return expectedValue.Equals(actualValue);
    }

For more context, see this article.

If you need to verify the calls in addition to just provide the instance, it gets somewhat complicated. The reason is that most calls does not actually belong to the ILogger interface itself.

I have written a more detailed answer here.

Here is a small overview.

Example of a method that I have made to work with NSubstitute:

public static class LoggerTestingExtensions
{
    public static void LogError(this ILogger logger, string message)
    {
        logger.Log(
            LogLevel.Error,
            0,
            Arg.Is<FormattedLogValues>(v => v.ToString() == message),
            Arg.Any<Exception>(),
            Arg.Any<Func<object, Exception, string>>());
    }

}

And this is how it can be used:

_logger.Received(1).LogError("Something bad happened");   

You should try this for mocking ILogger:

mock.Setup(m => m.Log<object>(It.IsAny<LogLevel>(),It.IsAny<EventId>(),It.IsAny<object>(),It.IsAny<Exception>(),It.IsAny<Func<object, Exception,string>>()))
    .Callback<LogLevel, EventId, object, Exception, Func<object, Exception, string>>((logLevel, eventId, obj, exception, func) => 
    {
        string msg = func.Invoke(obj, exception);
        Console.WriteLine(msg);
    });

This worked for me:

private FooController _fooController;
private Mock<ILogger<FooController>> _logger;

[TestInitialize]
public void Setup()
{
    _logger = new Mock<ILogger<FooController>>();
    _fooController = new FooController(_logger.Object);
}
Related