ILogger and IOptions in .NET unit tests: NullLogger, FakeLogger and Options.Create

xUnit Testing & CI/CD in .NET November 13, 2026 csharp

Use NullLogger.Instance when the logs don't matter, FakeLogger (Microsoft.Extensions.Diagnostics.Testing) when you need to assert that something was logged, and Options.Create to build options without any configuration.

csharp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// ======================================================================
// Q: How do you handle ILogger and IOptions in unit tests?
//
// Use NullLogger<T>.Instance when the logs don't matter, FakeLogger<T>
// (Microsoft.Extensions.Diagnostics.Testing) when you need to assert that
// something was logged, and Options.Create to build options without any
// configuration.
// ======================================================================

// You don't care about the logs
var sut = new PriceSync(repo, NullLogger<PriceSync>.Instance);

// You want to verify that a warning was logged (Microsoft.Extensions.Diagnostics.Testing)
var logger = new FakeLogger<SyncOrderToErpHandler>();
// ... act ...
Assert.Equal(LogLevel.Warning, logger.Collector.LatestRecord.Level);
Assert.Contains("rejected by ERP", logger.Collector.LatestRecord.Message);

// Options without configuration
var options = Options.Create(new ErpOptions { BaseUrl = "http://erp/", AttemptTimeoutSeconds = 5 });