How to unit test with ILogger in ASP.NET Core

Just mock it as well as any other dependency:

var mock = new Mock<ILogger<BlogController>>();
ILogger<BlogController> logger = mock.Object;

var controller = new BlogController(logger);

or use this short equivalent:

logger = Mock.Of<ILogger<BlogController>>()

You probably will need to install Microsoft.Extensions.Logging.Abstractions package to use ILogger<T>.

Moreover, you can create a real logger:

var serviceProvider = new ServiceCollection()

var factory = serviceProvider.GetService<ILoggerFactory>();

var logger = factory.CreateLogger<BlogController>();

Leave a Comment