Member-only story
Unit Testing with ILogger<T>
Some common ways to work with ILogger<T>
objects in unit testing.

EDIT 11/16/2020: The code has updated to .NET 5
EDIT 04/13/2020: The code has updated to .NET Core 3.1
An effective logging system is essential for application monitoring and analysis. .NET Core supports a logging API that works with a variety of built-in and third-party logging providers, such as the Console provider, the Azure Application Insights provider, Serilog, elma.io, and so on.
In order to create logs, we need to use an ILogger<T>
object, which is readily accessible in our applications. (1) In a web application or a hosted service, we can get an ILogger<T>
object from the native .NET Core dependency injection (DI) system. (2) In a non-host console application, we can use the LoggerFactory
to create an ILogger<T>
object.
Because ILogger<T>
objects are frequently used in controllers and service classes, we cannot avoid them in unit tests. In this post, we will go over some common ways to work with ILogger<T>
objects in unit testing. The full project can be found in this repository.
Table of Contents
1. Replace ILogger<T>
with NullLogger<T>
2. Create a Real ILogger<T>
that Logs to Console
3. Mock an ILogger<T>
Object
Let’s consider a service class CalculationService
that has a dependency on an ILogger<CalculationService>
object. We are going to test the contrived AddTwoPositiveNumbers(int a, int b)
method.
1. Replace ILogger<T>
with NullLogger<T>
The NullLogger<T>
implements ILogger<T>
and it is a minimalistic logger that does nothing. In other words, it doesn’t log messages to any place and it swallows exceptions. It is worth mentioning that both the ILogger<T>
interface and the NullLogger<T>
class are included in…