Table of Contents

FakeLoggerFixture

Assembly: FEFF.TestFixtures.AspNetCore.dll
Namespace: FEFF.TestFixtures.AspNetCore
Source: FakeLoggerFixture.cs

Overview

The FakeLoggerFixture is an extension to AppManagerFixture.
It adds the Microsoft.Extensions.Logging.Testing.FakeLoggerProvider to the logging subsystem of the application under test, allowing to capture and verify application logs during test execution.

Key Features

  • Log Capture: Collects all log entries generated by the application during test execution
  • Log Verification: Access captured logs through FakeLogCollector for assertions and debugging
  • Automatic Registration: Automatically registers the fake logger provider with the application's DI container
  • Integration with AppManagerFixture: Works seamlessly with other ASP.NET Core fixtures

Basic Usage

First, define your test application entry point with logging:

// ASP.NET Core test application entry point (Program.cs)
public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        var app = builder.Build();

        // Example endpoint that uses ILogger
        app.MapGet("/logging", (ILogger<Program> logger) =>
        {
            logger.LogInformation("log-1");
            logger.LogWarning("log-2");
            return Results.Ok();
        });

        app.Run();
    }
}

Then use the fixture in your tests:

using FEFF.TestFixtures.AspNetCore;
using Microsoft.Extensions.Logging.Testing;

public class LoggingTests
{
    protected IAppClientFixture Client { get; } = 
        TestContext.Current.GetFeffFixture<AppClientFixture<Program>>();

    // FakeLoggerFixture is automatically integrated with AppManagerFixture
    protected FakeLoggerFixture<Program> FakeLoggerFx { get; } = 
        TestContext.Current.GetFeffFixture<FakeLoggerFixture<Program>>();

    [Fact]
    public async Task Endpoint__should_log_messages()
    {
        // Act
        var resp = await Client.LazyValue.PostAsync("/logging", null, TestContext.Current.CancellationToken);
        resp.StatusCode.Should().Be(HttpStatusCode.OK);

        // Assert - verify captured logs
        var snapshot = FakeLoggerFx.Collector.GetSnapshot();

        JToken.FromObject(snapshot)
            .Should().ContainSubtree(
            """
            [
            {
                "Level": 2, // LogLevel.Information
                "Message": "log-1",
            },
            {
                "Level": 3, // LogLevel.Warning
                "Message": "log-2",
            }
            ]
            """);
    }
}

Type Arguments

Type Argument Constraint Description
TEntryPoint class The application entry point type. Typically the Startup or Program class.

Key Members

Member Type Description
Collector FakeLogCollector Gets the log collector for retrieving captured log entries. Use GetSnapshot() to access all captured logs.
LoggerProvider ILoggerProvider Gets the FakeLoggerProvider instance. Primarily used internally for registration.

Log Verification

The Microsoft.Extensions.Logging.Testing.FakeLogCollector provides methods to access captured logs:

Method Description
GetSnapshot() Returns an array of all captured log entries

Each log entry in the snapshot contains:

Property Type Description
Category string The logger category (typically the class name)
Level LogLevel The log level (Information, Warning, Error, etc.)
Message string The log message
Exception Exception Any exception associated with the log entry
Scopes ReadOnlyList<Dictionary<string, object>> Log scopes attached to the entry
Timestamp DateTimeOffset When the log was recorded
LevelEnabled bool Indicates if the log level was enabled

Example: Filtering Logs

var snapshot = FakeLoggerFx.Collector.GetSnapshot();

// Filter by log level
var warnings = snapshot.Where(x => x.Level == LogLevel.Warning).ToList();

// Filter by category
var myServiceLogs = snapshot.Where(x => x.Category.Contains("MyService")).ToList();

// Filter by message content
var errorLogs = snapshot.Where(x => x.Message.Contains("error")).ToList();

// Verify specific log exists
snapshot.Should().ContainSingle(x => 
    x.Level == LogLevel.Error && 
    x.Message == "Connection failed");

See Also

Link Description
API: FakeLoggerFixture API reference
FakeLoggerFixtureTests.cs Unit tests for FakeLoggerFixture
API Integration Example Integration test examples using FakeLoggerFixture
Microsoft.Extensions.Logging.Testing Documentation Official documentation for fake logging types
ASP.NET Core Logging ASP.NET Core logging overview