A helper library for NUnit tests with ASP.NET Core Kestrel that fixes Console.WriteLine and TestContext output not appearing in test results.
When testing ASP.NET Core applications with NUnit and WebApplicationFactory, output from Console.WriteLine and TestContext.WriteLine inside HTTP request handlers doesn't appear in test results. This is because NUnit's TestExecutionContext is stored in an AsyncLocal<T> that gets lost when Kestrel handles requests on different threads.
Issue Reference: nunit/nunit#4860
[Test]
public async Task TestEndpoint()
{
await using var factory = new WebApplicationFactory<Program>();
var client = factory.CreateClient();
var response = await client.GetAsync("/");
// Console.WriteLine from inside the endpoint handler won't appear! ❌
}This library provides a simple extension method that restores the NUnit test context for all HTTP requests, ensuring that all output appears in your test results.
dotnet add package Agoda.NUnit.KestrelLoggingSimply call .WithNUnitTestLogging(out var scope) on your WebApplicationFactory and dispose the scope when your test completes:
using Agoda.NUnit.KestrelLogging;
using Microsoft.AspNetCore.Mvc.Testing;
using NUnit.Framework;
[Test]
public async Task TestEndpoint()
{
// Create factory with NUnit logging support
await using var factory = new WebApplicationFactory<Program>()
.WithNUnitTestLogging(out var scope);
using (scope)
{
var client = factory.CreateClient();
var response = await client.GetAsync("/");
// Console.WriteLine from inside the endpoint handler will now appear! ✅
response.EnsureSuccessStatusCode();
}
}app.MapGet("/", () =>
{
Console.WriteLine("This will now appear in test output!");
TestContext.WriteLine("This works too!");
return "Hello World!";
});The library solves the problem by:
- Creating a unique token for each test instance
- Storing the NUnit test context associated with that token
- Adding middleware that restores the test context for each HTTP request
- Configuring logging to write to NUnit's test output
This ensures that the AsyncLocal<TestExecutionContext> is properly restored when Kestrel handles requests, making all output appear in test results.
- .NET 8.0 or later
- NUnit 4.0 or later
- Microsoft.AspNetCore.Mvc.Testing 8.0 or later
We welcome contributions! Please see CONTRIBUTING.md for guidelines.
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
Made with ❤️ by Agoda