skip to content

In ASP.NET Core 10, what changes when a test calls WebApplicationFactory<Program>.UseKestrel() before creating its first client?

level: seniorimportance: nice to knowfreq 18%

answer

  1. real sockets instead of in-memory
  2. call it before the host starts
  3. UseKestrel(0) for a dynamic port
  4. Server property throws NotSupportedException
  5. BaseAddress read from IServerAddressesFeature

basics

~20 s

UseKestrel() makes the factory host the app on real Kestrel sockets instead of TestServer, so a browser or another process can reach it. CreateClient then targets the bound address over a normal HttpClientHandler, and the factory's Server property throws.

solid answer

~40 s

`UseKestrel()`, `UseKestrel(int port)` and `UseKestrel(Action<KestrelServerOptions>)` must be called before the factory starts, that is before the first `CreateClient`, `Services` access or `StartServer()`; afterwards they throw `InvalidOperationException`. The factory then calls `UseKestrel` on the web host builder instead of registering `TestServer` as `IServer`, starts the host, reads the bound address from `IServerAddressesFeature` and copies it into `ClientOptions.BaseAddress`. `CreateClient()` returns an `HttpClient` over `HttpClientHandler`, still wrapped in the redirect and cookie handlers; `Services` works, but `Server` throws `NotSupportedException` because no `TestServer` exists. Without a port Kestrel binds whatever the app configures, falling back to `http://localhost:5000`, which collides when test classes run in parallel; `UseKestrel(0)` binds `http://127.0.0.1` on a free port. Reserve it for browser-driven tests and clients that need a real socket.

code

csharp · 10 lines
csharp
await using var factory = new WebApplicationFactory<Program>();
factory.UseKestrel(0);   // free port on 127.0.0.1
factory.StartServer();   // start now; UseKestrel would throw after this

var baseUrl = factory.ClientOptions.BaseAddress; // e.g. http://127.0.0.1:53817/

// hand baseUrl to a browser driver, or use the factory's own client
using var client = factory.CreateClient();
var response = await client.GetAsync("/jobs");
response.EnsureSuccessStatusCode();

go deeper

for a junior

Know that the factory normally uses an in-memory TestServer and that UseKestrel switches it to a real listening server.

for a middle

Explain the ordering rule, what CreateClient's base address becomes, and why Server throws once Kestrel is in use.

for a senior

Use UseKestrel(0) for browser and socket-level tests, avoid port collisions in parallel runs, and keep the bulk of the suite on TestServer.

for a principal

Decide which test categories justify real sockets, and budget their run time and flakiness against the defects only a real server reveals.

## Why a real server inside the factory By default `WebApplicationFactory<Program>` registers **`TestServer`** as the app's `IServer`. Requests from `CreateClient()` are handed to the pipeline in memory, which is fast and isolated but reachable only through that client. Some tests need an actual listening socket: a **Playwright** browser loading the job-board's pages, an external process such as a load or contract tool, or a client library that insists on opening its own connection. For those, the factory can host the same app on **Kestrel**. ## The API `WebApplicationFactory<TEntryPoint>` has three overloads: - `UseKestrel()` switches the server to Kestrel with the app's own endpoint configuration. - `UseKestrel(int port)` also rewrites the server addresses to `http://127.0.0.1:{port}` and sets `PreferHostingUrls`, so configured endpoints are ignored. Port `0` asks the operating system for a free port. - `UseKestrel(Action<KestrelServerOptions>)` lets the test configure Kestrel, for example `options.Listen(...)` with HTTPS or HTTP/2 settings. All three must run **before the host starts**. The factory starts lazily on the first `CreateClient()`, `CreateDefaultClient()`, `Services` or `StartServer()`; calling `UseKestrel` after that throws `InvalidOperationException` ("UseKestrel should be called before server initialization"). `StartServer()` is public, so a test can force the start, then read the address before handing it to a browser. ## What changes inside the factory | Aspect | Default (TestServer) | After `UseKestrel` | |---|---|---| | `IServer` | `TestServer` registered by the factory | Kestrel, via `UseKestrel` on the web host builder | | Transport | in-memory handler | TCP sockets on the bound address | | `CreateClient()` base address | `http://localhost` | the bound address, read from `IServerAddressesFeature` | | Inner handler | `TestServer.CreateHandler()` | a new `HttpClientHandler` | | `factory.Server` | the `TestServer` | throws `NotSupportedException` | | `factory.Services` | app services | app services | `CreateClient()` keeps adding the redirect and cookie handlers from `WebApplicationFactoryClientOptions`; only the innermost handler changes. When the host starts, the factory overwrites `ClientOptions.BaseAddress` with the address Kestrel actually bound; `CreateClient(options)` with an explicit `BaseAddress` uses the address it is given. ## Choosing a port With plain `UseKestrel()`, Kestrel binds what the app's configuration says: `Kestrel:Endpoints`, `urls`, `ASPNETCORE_URLS`. With none of those it falls back to **`http://localhost:5000`**. Two test classes, each with its own factory, then fight over the same port when the test framework runs them in parallel, and the second host fails to bind. `UseKestrel(0)` avoids that: each factory gets a free loopback port, and the factory publishes it through `ClientOptions.BaseAddress` for clients and browsers to use. ## Costs to weigh 1. **Speed.** Every request now crosses the TCP stack; the gap is small per request but adds up across large suites. 2. **Exposure.** A listening port is reachable by other local processes for the life of the test, so bind to loopback. 3. **API surface.** Code that reached into `factory.Server`, for example `Server.CreateWebSocketClient()` or `Server.CreateRequest(...)`, has to change, because there is no `TestServer` to return. 4. **Fidelity.** Real sockets bring real timeouts, connection limits and protocol negotiation into the test, which is the point for some tests and noise for most. ## Lifetime and disposal A Kestrel-hosted factory holds a real port until it is disposed. `DisposeAsync()` disposes the clients the factory created, then any derived factories, then stops the host with `StopAsync()` and disposes it, which closes the listening socket. Share the factory through the test framework's fixture so that happens once per class or collection, and avoid creating Kestrel factories inside loops or per test method, where slow teardown and port reuse turn into intermittent failures. The practical split is the default `TestServer` for the bulk of API tests and `UseKestrel(0)` for the handful that need a browser or a socket-level client.

  • A test that used factory.Server.CreateWebSocketClient() breaks after UseKestrel(0) is added. Why, and what replaces it?
    With Kestrel there is no `TestServer`, so the `Server` getter throws `NotSupportedException`. Connect a real client such as `ClientWebSocket` to `ws://` plus the host and port from `ClientOptions.BaseAddress`.
  • Two test classes each call UseKestrel() without a port and one fails to start. What happened?
    With no configured URLs Kestrel falls back to `http://localhost:5000`, so the second factory's host cannot bind the port the first one holds. `UseKestrel(0)` gives each factory its own free port.

  • UseKestrel can be called any time, even after the first CreateClient.
  • After UseKestrel, factory.Server still returns a usable TestServer.
  • UseKestrel() without a port always picks a free random port.
  • Switching to Kestrel removes the factory's redirect and cookie handlers.
  • Every WebApplicationFactory test should run on Kestrel for realism.