Lesson 84 of 93 · 6 min read · Updated

End-to-End Tests with Playwright for .NET: Real Browser, Real Kestrel Host

Integration tests with WebApplicationFactory stop at the HTTP layer. They never run the HTML and JavaScript that your users actually click. End-to-end tests close that gap: a real browser loads the page, the page calls the API, and the API talks to the database. This lesson shows how to start the real ASP.NET Core app on a Kestrel port inside the test process, drive it with Playwright's Chromium, and keep the tests few, stable and free of sleeps.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. Microsoft.Playwright.Xunit 1.65.0 (provides PageTest and Expect)
  4. Microsoft.AspNetCore.Mvc.Testing 11.0.0
  5. Microsoft.EntityFrameworkCore.Sqlite 11.0.0
  6. Chromium is downloaded on the first run (about 150 MB). Docker is not required.

The Page Under Test

The API serves a small static page from wwwroot/index.html. It has a form to add a book and a list of books. It is written without a framework on purpose: the test checks what the user sees, not how the page is built. The page is in Turkish, so the labels the tests use are Turkish too.

M09.IntegrationApi/wwwroot/index.html

<form id="add-book">
<label>ISBN <input name="isbn" required></label>
<label>Başlık <input name="title" required></label>
<label>Yazar <input name="author" required></label>
<label>Fiyat (TL) <input name="priceTry" type="number" step="0.01" required></label>
<label>Yayın yılı <input name="publishedYear" type="number" required></label>
<button type="submit">Kitap ekle</button>
<p class="error" data-testid="form-error" role="alert"></p>
</form>

<h2>Liste (<span data-testid="book-count">0</span>)</h2>
<ul data-testid="book-list"></ul>

Each input is wrapped in a <label>, so it has an accessible name. The error paragraph has role="alert". The list and counter have data-testid attributes. These are stable handles for tests. CSS classes can change without breaking anything.

Starting the Real App on a Real Port

WebApplicationFactory normally hosts the app on an in-memory TestServer, and a browser cannot connect to that. BooksAppServer uses the UseKestrel and StartServer support added in .NET 10 to start the same Program.cs on a real TCP port.

M09.IntegrationApi.E2E.Tests/Infrastructure/BooksAppServer.cs

public sealed class BooksAppServer : WebApplicationFactory<Program>, IAsyncLifetime
{
private readonly SqliteConnection _keepAlive = new(ConnectionString);
private const string ConnectionString = "DataSource=m09-e2e;Mode=Memory;Cache=Shared";

public string BaseUrl { get; private set; } = string.Empty;

public Task InitializeAsync()
{
// Downloads the browser if missing; does nothing if it exists (fast).
var exitCode = Microsoft.Playwright.Program.Main(["install", "chromium"]);
if (exitCode != 0)
{
throw new InvalidOperationException($"Playwright tarayıcı kurulumu başarısız (çıkış kodu {exitCode}).");
}

_keepAlive.Open();
// Port 0 = the operating system picks a free port → no conflicts in parallel CI jobs.
UseKestrel(0);
StartServer();
BaseUrl = Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.First();
return Task.CompletedTask;
}

protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Testing");
builder.ConfigureTestServices(services =>
{
services.RemoveAll<DbContextOptions<AppDbContext>>();
services.RemoveAll<AppDbContext>();
services.AddDbContext<AppDbContext>(options => options.UseSqlite(ConnectionString));

using var scope = services.BuildServiceProvider().CreateScope();
scope.ServiceProvider.GetRequiredService<AppDbContext>().Database.EnsureCreated();
});
}

Three details matter here.

  1. Microsoft.Playwright.Program.Main(["install", "chromium"]) installs the browser from .NET code. You do not need PowerShell or playwright.ps1. Later runs use the cache (~/Library/Caches/ms-playwright on macOS, ~/.cache/ms-playwright on Linux).
  2. UseKestrel(0) asks the operating system for a free port. The real address is read back from IServerAddressesFeature and becomes the browser's base URL.
  3. The database is a shared SQLite in-memory database (Mode=Memory;Cache=Shared). Kestrel handles requests on parallel threads, so each DbContext opens its own connection instead of sharing one. The _keepAlive connection stays open so the database is not deleted between requests.

The fixture also exposes ResetDatabaseAsync and SeedAsync, the same helpers as the integration-test factory.

Writing the Journeys

The test class inherits Playwright's PageTest, which gives each test a fresh browser context and Page. It shares one BooksAppServer through a collection fixture.

M09.IntegrationApi.E2E.Tests/BookCatalogJourneyTests.cs

[Collection(E2ECollection.Name)]
[Trait("Kapsam", "E2E")]
public class BookCatalogJourneyTests(BooksAppServer app) : PageTest
{
public override BrowserNewContextOptions ContextOptions() => new()
{
BaseURL = app.BaseUrl,
Locale = "tr-TR",
};

[Fact]
public async Task Customer_CanAddABook_AndSeeItInTheList()
{
await Page.GotoAsync("/");

await Page.GetByLabel("ISBN").FillAsync("978-3");
await Page.GetByLabel("Başlık").FillAsync("Domain-Driven Design");
await Page.GetByLabel("Yazar").FillAsync("Eric Evans");
await Page.GetByLabel("Fiyat (TL)").FillAsync("1200");
await Page.GetByLabel("Yayın yılı").FillAsync("2003");
await Page.GetByRole(AriaRole.Button, new() { Name = "Kitap ekle" }).ClickAsync();

await Expect(Page.GetByTestId("book-row"))
.ToHaveTextAsync("Domain-Driven Design — Eric Evans (978-3)");
}

[Fact]
public async Task AddingADuplicateIsbn_ShowsTheConflictMessage()
{
// Arrange — the same ISBN is already stored.
await app.SeedAsync(
new Book { Isbn = "978-4", Title = "Mevcut Kitap", Author = "Yazar", PriceTry = 100m, PublishedYear = 2020 });
await Page.GotoAsync("/");

// Act
await Page.GetByLabel("ISBN").FillAsync("978-4");
await Page.GetByLabel("Başlık").FillAsync("Başka Kitap");
await Page.GetByLabel("Yazar").FillAsync("Başka Yazar");
await Page.GetByLabel("Fiyat (TL)").FillAsync("200");
await Page.GetByLabel("Yayın yılı").FillAsync("2021");
await Page.GetByRole(AriaRole.Button, new() { Name = "Kitap ekle" }).ClickAsync();

// Assert — the user SEES the server's 409 message; the list does not change.
await Expect(Page.GetByRole(AriaRole.Alert)).ToContainTextAsync("zaten kayıtlı");
await Expect(Page.GetByTestId("book-row")).ToHaveCountAsync(1);
}
}

The locators target what a user sees: a field by its label, a button by its role and name, an alert by its role. When a locator needs a hook that is not visible, it uses data-testid. No CSS selectors, so a redesign does not break the test.

There is no Thread.Sleep or Task.Delay. Expect(...) retries its assertion until it passes or the timeout (5 seconds by default) expires. The page fetches the list asynchronously after the click, and the assertion simply waits for the new row.

The duplicate test seeds its existing book directly into the database instead of filling the form twice. Only the step under test goes through the UI. Using the UI for arrange steps would make the test slower and give it more ways to fail for reasons unrelated to what it checks.

Pitfall: Too Many End-to-End Tests

E2E tests sit at the top of the test pyramid. They are the slowest and most fragile tests you have. This project has only three, one per critical journey: the list loads, a user can add a book, and a duplicate shows the server's conflict message. The 409 status code is already proven by an integration test and the unique index by an EF Core test. The E2E test exists to prove that the page shows that message to the user, which no lower-level test can do.

When a journey fails, the test keeps a Playwright trace. InitializeAsync starts tracing with screenshots and DOM snapshots, and DisposeAsync saves the trace only if the test failed (TestOk is false), under bin/.../playwright-traces/*.zip. Open it at https://trace.playwright.dev to step through every action. Green tests leave nothing on disk.

Summary

  1. End-to-end tests run the real HTML, JavaScript, API and database together in a real browser.
  2. UseKestrel(0) plus StartServer() hosts the real Program.cs on a free TCP port that Playwright can reach.
  3. Use a shared SQLite in-memory database with a keep-alive connection, because Kestrel serves requests in parallel.
  4. Locate elements by role, label and data-testid; let Expect wait instead of sleeping.
  5. Keep E2E tests few, seed data directly, keep them in their own project, and save traces only for failures.