Skip to content

Integration and end-to-end testing with Playwright

Unit tests prove that each piece works; they cannot prove that the pieces fit. Routing that sends a request to the wrong handler, a JSON property renamed on one side, a validation rule that never runs, a SQL query that EF Core cannot translate, or a button that a CSS change hides: all of these pass unit tests and fail in production. Integration tests run several real components together, such as the HTTP pipeline, dependency injection, serialization and a database. End-to-end (E2E) tests drive the whole deployed application through its user interface, as a customer would.

Both are slower and more expensive than unit tests, so a suite has fewer of them and aims them at the seams. This page shows one of each for the invented OrdersPortal app. The C# integration tests were run with xUnit v3 4.0.3 and Microsoft.AspNetCore.Mvc.Testing 10.0.15 on .NET SDK 10.0.115. The Playwright tests were run with @playwright/test 1.65.0 and Chromium on Node.js 22, against a small local stand-in for the web app.

Topic Tooling Use it for
Integration testing WebApplicationFactory, Testcontainers, Supertest, FastAPI TestClient API endpoints through the real pipeline, database queries and migrations, message handlers
End-to-end testing with Playwright Playwright Test Critical user journeys in real browsers, across the deployed stack

Unit testing and test doubles are covered in unit testing; the test pyramid is in the testing overview.

An integration test exercises real collaborators and replaces only what it must: external services you do not control, and sometimes the database. For ASP.NET Core, WebApplicationFactory<Program> from Microsoft.AspNetCore.Mvc.Testing boots the actual application in memory (the same Program.cs, middleware, routing, validation, JSON settings and DI registrations) on a TestServer, and CreateClient() returns an HttpClient wired to it with no network port. Override ConfigureWebHost and call ConfigureTestServices to swap registrations; it runs after the app’s own registrations, so your replacements win.

For the database, choose deliberately. An in-memory fake (as below) keeps tests fast and tests everything except SQL. To test queries, constraints and migrations, run the real engine: Testcontainers (Testcontainers.MsSql, Testcontainers.PostgreSql) starts a disposable database container per test run, which needs Docker on the build agent. The EF Core in-memory provider and SQLite in-memory behave differently from SQL Server and PostgreSQL (no real transactions or different SQL), so treat them as fakes, not as database tests. The same approach exists in other stacks: Supertest against an Express or Fastify app in Node.js, and FastAPI’s TestClient with dependency overrides in Python.

The API under test, src/OrdersPortal.Api/Program.cs (a web project with Microsoft.NET.Sdk.Web and net10.0):

using System.ComponentModel.DataAnnotations;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddValidation();
builder.Services.AddProblemDetails();
builder.Services.AddSingleton<IOrderStore, SqlOrderStore>(); // the real store talks to SQL Server
var app = builder.Build();
app.MapPost("/api/orders", async (CreateOrder request, IOrderStore store) =>
{
var order = await store.AddAsync(request);
return Results.Created($"/api/orders/{order.Id}", order);
});
app.MapGet("/api/orders/{id:int}", async (int id, IOrderStore store) =>
await store.FindAsync(id) is { } order ? Results.Ok(order) : Results.NotFound());
app.Run();
public record CreateOrder([Required, EmailAddress] string CustomerEmail, [Range(1, 100)] int Quantity);
public record Order(int Id, string CustomerEmail, int Quantity);
public interface IOrderStore
{
Task<Order> AddAsync(CreateOrder request);
Task<Order?> FindAsync(int id);
}
public sealed class SqlOrderStore : IOrderStore
{
public Task<Order> AddAsync(CreateOrder request) => throw new NotImplementedException("needs a database");
public Task<Order?> FindAsync(int id) => throw new NotImplementedException("needs a database");
}
public partial class Program; // lets the test project reference the entry point

The test project, tests/OrdersPortal.Api.Tests/OrdersPortal.Api.Tests.csproj, with the same global.json as in unit testing:

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.15" />
<PackageReference Include="xunit.v3" Version="4.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../../src/OrdersPortal.Api/OrdersPortal.Api.csproj" />
</ItemGroup>
</Project>

OrdersApiTests.cs:

using System.Collections.Concurrent;
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Xunit;
// Boots the real Program (routing, validation, serialization, DI) in memory,
// replacing only the database-backed store.
public sealed class OrdersApiFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder) =>
builder.ConfigureTestServices(services =>
{
services.RemoveAll<IOrderStore>();
services.AddSingleton<IOrderStore, InMemoryOrderStore>();
});
}
public sealed class InMemoryOrderStore : IOrderStore
{
private readonly ConcurrentDictionary<int, Order> _orders = new();
private int _next = 1000;
public Task<Order> AddAsync(CreateOrder r)
{
var order = new Order(Interlocked.Increment(ref _next), r.CustomerEmail, r.Quantity);
_orders[order.Id] = order;
return Task.FromResult(order);
}
public Task<Order?> FindAsync(int id) => Task.FromResult(_orders.GetValueOrDefault(id));
}
public class OrdersApiTests(OrdersApiFactory factory) : IClassFixture<OrdersApiFactory>
{
private readonly HttpClient _client = factory.CreateClient();
[Fact]
public async Task Post_then_get_round_trips_the_order()
{
var created = await _client.PostAsJsonAsync("/api/orders",
new { customerEmail = "dana@example.test", quantity = 2 }, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.Created, created.StatusCode);
var location = created.Headers.Location!;
var order = await _client.GetFromJsonAsync<Order>(location, TestContext.Current.CancellationToken);
Assert.Equal("dana@example.test", order!.CustomerEmail);
}
[Fact]
public async Task Invalid_order_returns_400_problem_details()
{
var response = await _client.PostAsJsonAsync("/api/orders",
new { customerEmail = "not-an-email", quantity = 0 }, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType!.MediaType);
var body = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.Contains("CustomerEmail", body);
Assert.Contains("Quantity", body);
}
[Fact]
public async Task Unknown_order_returns_404()
{
var response = await _client.GetAsync("/api/orders/999999", TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
}

Run dotnet test in the test folder. Output:

Test run summary: Passed!
total: 3
failed: 0
succeeded: 3
skipped: 0

The second test proves something no unit test could: that AddValidation() is registered, the record’s attributes are discovered, and the response really is application/problem+json.

Pitfalls:

  • Shared state between tests. An IClassFixture factory is shared by every test in the class, so data created by one test is visible to the next. Create unique data per test (new IDs, unique emails) or reset the store, and never assert on “the number of orders in the system”.
  • Testing against shared environments. Integration tests that hit a shared dev database interfere with each other and with people. Use an in-memory replacement or a disposable container per run.
  • Copying production secrets into tests. Override configuration in the factory (ConfigureAppConfiguration with in-memory values) instead of reading real connection strings.

Playwright is Microsoft’s open-source browser automation framework. One API drives Chromium, Firefox and WebKit (the engine behind Safari), headless or headed, on Windows, Linux and macOS. Playwright Test, the Node.js test runner, adds parallel workers, retries, projects per browser or device, HTML reports, and traces you can step through after a CI failure; libraries also exist for .NET, Python and Java. Start a project with npm init playwright@latest, which installs @playwright/test and the browsers (npx playwright install --with-deps on CI).

Two features make Playwright tests stable. Locators find elements the way users and assistive technology do: getByRole('button', { name: 'Sign in' }), getByLabel('Email'), getByText, and getByTestId as a fallback, instead of brittle CSS paths. Auto-waiting and web-first assertions such as await expect(locator).toHaveText(...) retry until the condition holds or a timeout expires, so there is no need for manual sleeps. The page object model keeps selectors and actions for a page in one class so tests read as user steps. The webServer option starts the app before the tests.

playwright.config.ts:

import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
reporter: 'list',
use: {
baseURL: 'http://localhost:4173',
trace: 'on-first-retry',
},
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
webServer: {
command: 'node app/server.mjs',
url: 'http://localhost:4173/login',
reuseExistingServer: !process.env.CI,
},
});

tests/pages/login-page.ts:

import type { Locator, Page } from '@playwright/test';
export class LoginPage {
readonly email: Locator;
readonly password: Locator;
readonly submit: Locator;
constructor(private readonly page: Page) {
this.email = page.getByLabel('Email');
this.password = page.getByLabel('Password');
this.submit = page.getByRole('button', { name: 'Sign in' });
}
async goto() {
await this.page.goto('/login');
}
async signIn(email: string, password: string) {
await this.email.fill(email);
await this.password.fill(password);
await this.submit.click();
}
}

tests/orders.spec.ts:

import { expect, test } from '@playwright/test';
import { LoginPage } from './pages/login-page';
test('customer signs in and sees their orders', async ({ page }) => {
const login = new LoginPage(page);
await login.goto();
await login.signIn('dana@example.test', 'correct-horse');
await expect(page).toHaveURL(/\/orders/);
await expect(page.getByRole('heading', { level: 1 })).toHaveText('Orders for dana@example.test');
await expect(page.getByRole('row')).toHaveCount(2);
await expect(page.getByRole('row', { name: /1002/ })).toContainText('Pending');
});
test('the browser blocks submitting an empty form', async ({ page }) => {
const login = new LoginPage(page);
await login.goto();
await login.submit.click();
await expect(page).toHaveURL(/\/login$/);
});

Run npx playwright test. Output:

Running 2 tests using 2 workers
✓ 2 [chromium] › tests/orders.spec.ts:15:1 › the browser blocks submitting an empty form (308ms)
✓ 1 [chromium] › tests/orders.spec.ts:4:1 › customer signs in and sees their orders (405ms)
2 passed (1.5s)

The app behind node app/server.mjs was a minimal stand-in with a sign-in form and an orders table, enough to exercise the page object and assertions. In CI, upload playwright-report/ and test-results/ as artifacts so traces are available when a retry was needed.

Pitfalls:

  • Too many E2E tests. They are the slowest and most fragile layer. Cover the few journeys that make money or lose it (sign in, checkout, payment), and push detailed cases down to integration and unit tests.
  • Fixed sleeps and CSS selectors. waitForTimeout(3000) and .btn-primary > span break on the next redesign or slow CI agent. Use role-based locators and web-first assertions.
  • Tests that depend on each other or on shared accounts. Each test gets a fresh browser context; create its own data through an API call or fixture, and use storageState to reuse a signed-in session safely.
Question you want answered Test type
Does this pricing rule return the right value? Unit test
Does POST /api/orders validate, serialize and return 201 with a Location header? Integration test with WebApplicationFactory
Does this EF Core query translate and return the right rows on SQL Server? Integration test with Testcontainers
Can a customer sign in and place an order in Safari and Chrome? Playwright E2E test
Does the API still honor the contract the mobile app expects? Contract test, or integration tests on the published OpenAPI schema

What does WebApplicationFactory give you that unit tests do not? It runs the real application pipeline in memory: middleware order, routing, model binding, validation, serialization, filters and DI wiring. Tests send real HTTP requests through an HttpClient without opening a port, and can replace individual services with ConfigureTestServices.

Why not use the EF Core in-memory provider for database tests? It is not a relational database: no SQL translation, no constraints, no transactions in the same way, and case sensitivity differs. Tests can pass while the real query fails. Use the real engine in a container for database behavior, and a fake repository when you only need a stand-in.

What makes Playwright tests less flaky than older Selenium suites? Locators re-resolve the element on every action and actions auto-wait until the element is visible, stable, enabled and receiving events; web-first assertions retry until they pass or time out. Each test runs in an isolated browser context, and traces make failures diagnosable.

How many E2E tests should a system have? As few as cover the critical journeys end to end, typically tens rather than thousands. Everything that can be tested lower down should be, because E2E tests are slow, need a full environment and fail for many unrelated reasons.

Senior scenario: OrdersPortal deploys several times a day, and the 40-minute E2E suite blocks releases and fails on unrelated flakiness. What do you change? Rebalance the pyramid: map each E2E test to the risk it covers, delete or move to integration tests the ones that only check API or validation behavior, and keep a small smoke suite of critical journeys that runs on every deployment in parallel shards. Fix flakiness at the source (role-based locators, web-first assertions, per-test data created through the API, no shared accounts), track flaky tests with retries reported rather than hidden, and run the full regression suite on a schedule or before major releases rather than on every commit. Add WebApplicationFactory and Testcontainers tests so most regressions are caught in minutes.