In a previous blog post, I introduced the NuGet package Nwwz.Mvc.Testing. This package was designed to make it possible to make the WebApplicationFactory listen on a rela port to that you can use it with Playwright.

The package implements a different WebApplicationFactory that spin up a Kestrel instance instead ot the in-memory TestServer.

With the release of .NET 10, this workaround is no longer necessary. Microsoft has introduced a native way to run WebApplicationFactory using Kestrel.

WebApplicationFactory.UseKestrel()

In .NET 10, the WebApplicationFactory has been enhanced with a new method: UseKestrel(). This method tells the factory to use a real Kestrel server instead of the in-memory TestServer.

This is exactly what Nwwz.Mvc.Testing aimed to do, but now it’s built right into the framework.

How to use it

Setting it up is now incredibly straightforward. You no longer need any custom packages or complex CreateHost overrides. Jus use the new UseKestrel() and StartServer():

Assuming you have the default dotnet Weatherforcast WebApi project under test. You now can do this:

public class TestWithRealPort : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;

    public TestWithRealPort(WebApplicationFactory<Program> factory)
    {
        _factory = factory;
        _factory.UseKestrel();
        _factory.StartServer();
    }

    [Fact]
    public async Task Get_EndpointsReturnSuccessAndCorrectContentType()
    {
        // Arrange
        var playwright = await Playwright.CreateAsync();
        var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
        {
            Headless = false, // To see something happening
            SlowMo = 2000 // Slow it down a bit so you can read along
        });
        var context = await browser.NewContextAsync();
        var page = await context.NewPageAsync();
        
        var baseAddress = _factory.ClientOptions.BaseAddress;

        // Act
        await page.GotoAsync(baseAddress + "weatherforecast");

        // Assert
        Assert.Contains("temperatureC", await page.ContentAsync());
    }
}

For a complete example go to: https://github.com/netwatwezoeken/full-integration-testing/tree/main

Nwwz.Mvc.Testing is now obsolete

Since this functionality is now part of the standard .NET library, Nwwz.Mvc.Testing is obsolete. As of version 1.1.0 it will give you a warning when using it in .NET 10.

I highly recommend migrating to .NET 10, and using the native UseKestrel() implementation. The migration should be minimal, as the concepts are identical.

Happy testing!