In an ASP.NET Core 10 unit test, why can't Moq verify logger.LogWarning(...) directly, and what does FakeLogger<T> offer instead?
answer
- an extension over Log<TState>
- Microsoft.Extensions.Diagnostics.Testing package
- LatestRecord and Collector.GetSnapshot()
- Level, Message, Exception, structured state
- AddFakeLogging() and GetFakeLogCollector()
basics
~10 sLogWarning is an extension method that calls ILogger.Log<TState>, so Moq rejects it with NotSupportedException. FakeLogger<T> from Microsoft.Extensions.Diagnostics.Testing records each entry as a FakeLogRecord with level, message, exception and structured state to assert on.
solid answer
~40 s`LogWarning`, `LogInformation` and friends are static methods in `LoggerExtensions`; they format nothing themselves but call the one interface member, `ILogger.Log<TState>(LogLevel, EventId, TState, Exception?, Func<TState, Exception?, string>)`. Moq refuses to set up or verify an extension method, and verifying `Log<TState>` needs `It.IsAnyType` matchers and string matching on the state, which is brittle. `FakeLogger<T>` (package `Microsoft.Extensions.Diagnostics.Testing`, from dotnet/extensions) implements `ILogger<T>`, so you pass it where the service expects its logger. Every call becomes a `FakeLogRecord` with `Level`, `Id`, `Message` (the formatted text), `Exception`, `Category`, `Scopes` and `GetStructuredStateValue("Code")` for template values. Read the last entry with `LatestRecord`, which throws `InvalidOperationException` when nothing was logged, or all entries with `Collector.GetSnapshot()`. For DI-built object graphs, `services.AddFakeLogging()` plus `provider.GetFakeLogCollector()` captures logs from every category.
code
csharp · 16 linesusing Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Xunit;
[Fact]
public async Task Expired_coupon_logs_a_warning_with_the_code()
{
var logger = new FakeLogger<CouponService>();
var service = new CouponService(new InMemoryCoupons(expired: "SPRING10"), logger);
await service.TryRedeemAsync("SPRING10", CancellationToken.None);
var record = logger.LatestRecord;
Assert.Equal(LogLevel.Warning, record.Level);
Assert.Equal("SPRING10", record.GetStructuredStateValue("Code"));
}go deeper
Know that you test logging with a recording fake logger, not by mocking LogWarning, and where FakeLogger<T> comes from.
Explain the extension-method chain down to Log<TState>, then read level, message, exception and structured values from FakeLogRecord.
Assert only log entries that are requirements, test structured values rather than prose, and capture whole containers with AddFakeLogging when needed.
Treat log templates that feed alerts as contracts with tests, and keep incidental logging out of assertions so refactors stay cheap.
## Why logging is awkward to mock ASP.NET Core code logs through `ILogger<T>`, but it almost never calls the interface directly. `logger.LogWarning("Coupon {Code} expired", code)` compiles into a call to the static `LoggerExtensions.LogWarning`, which wraps the message template and arguments in a state object and calls **`ILogger.Log<TState>`**. Source-generated `[LoggerMessage]` methods end up at the same interface member. That has two consequences for a proxy-based mock: - **Moq cannot see the extension method.** `Setup` or `Verify` on `l => l.LogWarning(...)` throws `NotSupportedException` with a message saying extension methods may not be used in setup or verification expressions. - **Verifying `Log<TState>` is brittle.** The state type is internal and generic, so the test needs `It.IsAnyType`, a predicate that calls `ToString()` on the state, and a matcher for the formatter delegate. The test then breaks on harmless wording changes. ## FakeLogger in practice The **`Microsoft.Extensions.Diagnostics.Testing`** package from dotnet/extensions ships an in-memory logger built for assertions: 1. Create `var logger = new FakeLogger<CouponService>();` and pass it to the service constructor that takes `ILogger<CouponService>`. 2. Exercise the code. 3. Inspect the records. | Member | What it gives you | |---|---| | `logger.LatestRecord` | the most recent `FakeLogRecord`; throws `InvalidOperationException` if none | | `logger.Collector.GetSnapshot()` | every record so far; pass `clear: true` to reset | | `logger.Collector.Count` | number of records | | `record.Level`, `record.Id` | the `LogLevel` and `EventId` | | `record.Message` | the fully formatted message | | `record.Exception` | the exception passed to the log call | | `record.GetStructuredStateValue("Code")` | the value bound to `{Code}` in the template | | `record.Scopes` | scope states active at the time | All levels are enabled by default. `logger.ControlLevel(LogLevel.Debug, false)` disables one, which lets you test code that checks `IsEnabled` before doing expensive work; records for disabled levels are still collected with `LevelEnabled` set to `false` unless the collector options say otherwise. ## Several loggers, or a whole container - A single **`FakeLogCollector`** can be shared by several `FakeLogger` instances, giving one ordered stream across classes. - For graphs built through dependency injection, **`services.AddFakeLogging()`** registers a fake logger provider and **`provider.GetFakeLogCollector()`** returns the collector, so every `ILogger<T>` the container hands out writes into it. - `FakeLogCollectorOptions` can filter by category or level and can take a `TimeProvider`, so record timestamps follow a `FakeTimeProvider` in time-sensitive tests. ## What to assert, and what not to - Assert the **level** and the **structured values** that operations teams rely on, for example that an expired coupon logs a warning with the `Code` value. - Prefer `GetStructuredStateValue` over substring checks on `Message`; the template's placeholders are the contract that log queries depend on, the prose around them is not. - Assert the **exception** is attached when the code logs a caught failure, because a message without the exception loses the stack trace in production. - Do not assert every debug line. Log assertions are useful where the log entry is a requirement, such as an audit or an alert trigger, and noise elsewhere. ## If you must verify with Moq Teams with existing Moq-based suites sometimes verify the interface member directly. It works, but every part of the expression is ceremony: - the level as `LogLevel.Warning`; - `It.IsAny<EventId>()`; - `It.Is<It.IsAnyType>((state, _) => state.ToString()!.Contains("expired"))` for the state; - `It.IsAny<Exception?>()`; - `It.IsAny<Func<It.IsAnyType, Exception?, string>>()` for the formatter. The predicate depends on how the state formats itself, so it breaks on harmless template edits, and the failure message shows generic plumbing instead of the log text. `FakeLogger<T>` replaces all of it with a record you can read. ## Scopes Code that wraps work in `logger.BeginScope(...)` can be checked too: each `FakeLogRecord.Scopes` lists the scope states active when the entry was written, so a test can prove that a coupon redemption logs inside a scope carrying the basket id. ## When NullLogger is enough When a test does not care about logging, `NullLogger<T>.Instance` from `Microsoft.Extensions.Logging.Abstractions` satisfies the constructor without recording anything. Use `FakeLogger<T>` only where a log entry is part of the expected behaviour.
- How do you assert that the service logged nothing at Warning or above?Take `logger.Collector.GetSnapshot()` and assert that no record has `Level >= LogLevel.Warning`. Avoid `LatestRecord` for this, because it throws `InvalidOperationException` when nothing was logged at all.
- Your service logs through a [LoggerMessage] source-generated method. Does FakeLogger still capture it?Yes. Generated methods call `ILogger.Log<TState>` on the logger they receive, so `FakeLogger<T>` records the entry with its level, event id and structured values like any other call.
- Moq can Setup and Verify logger.LogWarning like any interface method.
- FakeLogger.LatestRecord returns null when nothing has been logged.
- Asserting substrings of the formatted message is the robust way to test logs.
- FakeLogger ships inside Microsoft.Extensions.Logging itself, no extra package needed.
- Every unit test should assert on all log lines its code writes.