skip to content

WebApplicationFactory Tests

WebApplicationFactory boots the real app on an in-memory TestServer, so a test sends HTTP through the whole pipeline with chosen services swapped. Interviewers check isolation and overrides.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

5

In ASP.NET Core 10, what does WebApplicationFactory<Program> do when a test calls CreateClient, and what must the projects provide?

level: juniorimportance: must knowfreq 74%

answer

  1. Microsoft.AspNetCore.Mvc.Testing package
  2. Program.cs really runs
  3. TestServer registered as IServer
  4. http://localhost, redirects and cookies on
  5. ASP0027: Program is generated in 10

basics

~20 s

WebApplicationFactory<Program> runs the app's real Program.cs inside the test process, swaps the server for an in-memory TestServer and returns an HttpClient wired to it, so requests cross the whole middleware pipeline without opening a socket.

solid answer

~40 s

`WebApplicationFactory<TEntryPoint>` (package `Microsoft.AspNetCore.Mvc.Testing`) finds the assembly that holds `Program`, checks that its `.deps.json` sits beside the tests, sets the content root to the app project's folder and the environment to `Development`, then runs `Program.cs` and registers `TestServer` as the `IServer`. The first `CreateClient()` starts the host lazily and returns an `HttpClient` with base address `http://localhost` that follows up to 7 redirects and keeps cookies; `WebApplicationFactoryClientOptions` changes that per client. The test project needs the package and a `ProjectReference` to the app. `Program` must also be visible to the test assembly: before .NET 10 the compiler-generated `Program` of a top-level-statement app was internal, so teams added `public partial class Program { }`. In ASP.NET Core 10 a source generator emits that declaration, and analyzer `ASP0027` flags a hand-written one as unnecessary.

code

csharp · 17 lines
csharp
using System.Net;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;

public class JobListingTests(WebApplicationFactory<Program> factory)
    : IClassFixture<WebApplicationFactory<Program>>
{
    [Fact]
    public async Task Open_jobs_endpoint_returns_ok()
    {
        using var client = factory.CreateClient();

        var response = await client.GetAsync("/jobs?status=open");

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }
}

go deeper

for a junior

Recall the package name, that the app's own Program.cs runs, that requests go to an in-memory TestServer, and that CreateClient hands back an HttpClient aimed at http://localhost.

for a middle

Explain the lazy start on first use, the Development default, the deps.json and content-root lookups, and what AllowAutoRedirect and HandleCookies do to the client you get back.

for a senior

Show you know what really runs: startup side effects execute per factory, so share one factory per test class and keep seeding idempotent, and know why ASP0027 now flags old Program declarations.

for a principal

Weigh the cost of booting the real host per factory against the fidelity it buys, and set suite rules on factory sharing so startup time stays bounded as the API grows.

## What the factory is `WebApplicationFactory<TEntryPoint>` lives in the **`Microsoft.AspNetCore.Mvc.Testing`** NuGet package (10.0.12 for an ASP.NET Core 10 app). Despite the `Mvc` in the name it works for any ASP.NET Core app: Minimal APIs, controllers, Razor Pages, Blazor. `TEntryPoint` is any type in the app's entry-point assembly; in practice it is `Program`. The factory boots **the app's own startup code**, so every service registration, middleware call and endpoint mapping in `Program.cs` is exercised, and only the server is swapped. ## What happens on the first CreateClient Nothing starts in the constructor. The first call to `CreateClient()`, `CreateDefaultClient()`, `Services` or `StartServer()` does the work: 1. **Entry point check.** If the type's assembly has no entry point, the factory throws `InvalidOperationException`, the usual sign that a class-library type was passed. 2. **deps.json check.** The app's `<AppName>.deps.json` must sit next to the test binaries; the package's MSBuild targets copy it there on build. A missing file throws with a message pointing at `PreserveCompilationContext` and shadow copying. 3. **Content root.** The factory reads the `MvcTestingAppManifest.json` the same targets generate (or a `WebApplicationFactoryContentRootAttribute`), then falls back to the solution folder plus the assembly name, so `appsettings.json` and views come from the app project. 4. **Host settings.** It sets the application name to the app's assembly name and the environment to **`Development`**. 5. **Running Program.cs.** `HostFactoryResolver` invokes the entry point and intercepts the host as `WebApplicationBuilder.Build()` creates it, replaying the factory's own configuration callbacks at that moment. 6. **Server swap.** It registers `TestServer` as the `IServer` singleton and starts the host. Because the entry point really runs, code in `Program.cs` between `Build()` and `Run()` (seeding, migrations, warm-up calls) runs for every factory instance too. ## What the returned HttpClient does `TestServer` hands requests straight to the app's `RequestDelegate` in memory: no port, no TLS, no network stack. The client is configured by `WebApplicationFactoryClientOptions`: | Option | Default | Effect | |---|---|---| | `BaseAddress` | `http://localhost` | Relative URIs in the test resolve against it | | `AllowAutoRedirect` | `true` | Adds a `RedirectHandler` that follows 3xx responses | | `MaxAutomaticRedirections` | `7` | Ceiling for that handler | | `HandleCookies` | `true` | Adds a `CookieContainerHandler`, so cookies set by one response go out on the next request | The parameterless `CreateClient()` uses the factory's `ClientOptions`; `CreateClient(options)` takes its own. `CreateDefaultClient(params DelegatingHandler[])` skips both built-in handlers and chains yours in front of the server handler. The factory tracks every client it created and disposes them, the host and any derived factories when it is disposed itself. ## Making Program reachable A top-level-statement `Program.cs` compiles into a `Program` class the compiler generates as **internal**. A separate test project cannot name an internal type, so `WebApplicationFactory<Program>` failed to compile until the app added: ```csharp public partial class Program { } ``` In **ASP.NET Core 10** the framework ships a source generator that emits exactly that declaration when the entry point's `Program` is generated, not already public and not declared in user code. The analyzer **`ASP0027`** (severity Info) reports an existing hand-written declaration as unnecessary, with a code fix that removes it. Apps with an explicit `class Program { static void Main… }` are left alone; make that class public yourself. ## What the projects need - The test project references `Microsoft.AspNetCore.Mvc.Testing` and the app project by `ProjectReference`; it does not need direct references to `Microsoft.AspNetCore.TestHost`. - The test framework is your choice: xunit.v3, NUnit or MSTest all work, because the factory is an ordinary disposable object. - Program.cs should pass `args` to `WebApplication.CreateBuilder(args)`, as the templates do; the factory delivers host settings such as the environment through those arguments. - Tests must run from the build output, or from a copy that includes the app's `.deps.json`. A runner that shadow-copies assemblies elsewhere triggers the missing-deps-file error, whose message names shadow copying as a common cause. - One factory per test class (or per shared fixture) is the normal unit of reuse; creating clients from it is cheap, booting it is not. ## Mistakes interviewers listen for - Expecting a 302 from a login-protected Razor page and getting 200, because the default client followed the redirect to the login page. - Believing the factory listens on a real Kestrel port; it uses Kestrel only after `UseKestrel()` is called. - Assuming tests run as `Production`; the default is `Development`, with everything that environment switches on. - Building a fresh factory in every test method, which re-runs the whole startup each time instead of sharing one factory across a class.

  • Why does a test that expects a 302 from a login-protected Razor page receive a 200?
    `CreateClient()` uses `AllowAutoRedirect = true` by default, so a `RedirectHandler` follows the 302 to the login page and the test sees that page's 200. Create the client with `new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }` to assert the status and `Location` header directly.
  • Code in Program.cs seeds reference data after app.Build(). Does it run under WebApplicationFactory?
    Yes. The factory runs the real entry point and only intercepts the host when it is built, so seeding, migrations or warm-up code between `Build()` and `Run()` executes for every factory instance. Each derived factory from `WithWebHostBuilder` runs it again.
  • What does CreateDefaultClient give you that CreateClient does not?
    `CreateDefaultClient(params DelegatingHandler[])` builds a client from your own handler chain in front of the server handler and leaves out the redirect and cookie handlers that `CreateClient` adds from `WebApplicationFactoryClientOptions`. It suits tests that need a custom header-stamping or logging handler.

  • WebApplicationFactory starts Kestrel on a random port for every test.
  • The factory skips Program.cs and builds its own service container.
  • Tests under the factory run in the Production environment by default.
  • CreateClient returns a client that never follows redirects or stores cookies.
  • Every ASP.NET Core 10 app still needs a hand-written public partial class Program.

Assumes ASP.NET Core 10: the public partial Program class is source-generated and ASP0027 flags a manual one; earlier versions needed the declaration.

open as a page

In an ASP.NET Core 10 WebApplicationFactory test, how do you replace the job-board API's registered e-mail sender with a fake for one test?

level: middleimportance: must knowfreq 66%

basics

~10 s

Call factory.WithWebHostBuilder(b => b.ConfigureTestServices(s => { s.RemoveAll<IMailSender>(); s.AddSingleton<IMailSender>(fake); })). The callback runs after Program.cs's registrations, and the derived factory boots its own app, leaving the shared factory untouched.

open as a page

In an ASP.NET Core 10 WebApplicationFactory test, how do you make calls to the job-board API's [Authorize] endpoints run as a chosen signed-in user?

level: middleimportance: should knowfreq 52%

basics

~10 s

Register a test AuthenticationHandler under its own scheme name in ConfigureTestServices, make it the default authenticate and challenge scheme, and have it return AuthenticateResult.Success with a ticket carrying the claims the test needs.

open as a page

A WebApplicationFactory suite for an ASP.NET Core 10 API passes on developers' machines but fails in CI with a missing connection string. How do the factory's environment defaults explain it?

level: seniorimportance: should knowfreq 38%

basics

~10 s

The factory runs the app in Development, so WebApplication.CreateBuilder loads each developer's user secrets, which CI lacks. Pin the environment with UseEnvironment and supply test settings explicitly through UseSetting or ConfigureAppConfiguration.

open as a page

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%

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.

open as a page