skip to content

App Testing Practice

Testing an ASP.NET Core app at each level: WebApplicationFactory integration tests, unit tests with mocking libraries, containerised databases and generated data. Interviewers probe where each fits.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

21

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

With Bogus, how do you build a Faker<Patient> that generates realistic patient records for an ASP.NET Core clinic-scheduling test suite?

level: juniorimportance: must knowfreq 48%

basics

~10 s

Create new Faker<Patient>() and add a RuleFor per property, drawing values from the Faker hub (f.Name.FirstName(), f.Internet.Email(...), f.Date.PastDateOnly(...)). Generate() returns one patient and Generate(50) a list; StrictMode(true) fails when a property has no rule.

open as a page

With Moq 4.21, how do you stub a coupon repository and verify an event was published when unit testing a grocery app's discount handler?

level: juniorimportance: must knowfreq 72%

basics

~20 s

Create a Mock<ICouponRepository>, Setup the lookup with It.IsAny<CancellationToken>() and ReturnsAsync(coupon), pass mock.Object to the handler, then call Verify on the event publisher's mock with Times.Once(). Calls you never set up return defaults rather than failing.

open as a page

How do you run ASP.NET Core integration tests for an order-management API against a real PostgreSQL started with Testcontainers?

level: middleimportance: must knowfreq 55%

basics

~10 s

Start a Testcontainers PostgreSqlBuilder container with a pinned image once per test run, pass its GetConnectionString() to WebApplicationFactory<Program> as the app's connection string, apply migrations once, and reset the data between tests.

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 unit test, how do you stub HttpClient responses for a grocery app's loyalty-points client without calling the real API?

level: middleimportance: must knowfreq 60%

basics

~20 s

Give the client an HttpClient built on a stub HttpMessageHandler whose SendAsync returns canned responses. HttpClient's GetAsync and PostAsync are not virtual, so mocking HttpClient itself fails; the handler is the seam every request passes through.

open as a page

With Testcontainers for .NET, what does new PostgreSqlBuilder("postgres:17").Build() give you, and how does a test connect to it?

level: juniorimportance: should knowfreq 42%

basics

~20 s

Build() returns a PostgreSqlContainer that is configured but not running. After await StartAsync(), GetConnectionString() returns a Host, Port, Database, Username and Password string pointing at the container's randomly mapped port, which the test passes to its DbContext or app.

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

In AutoFixture, what do Create, Build<T>().With and Freeze do, and how does AutoMoqCustomization supply a service's constructor dependencies?

level: middleimportance: should knowfreq 34%

basics

~20 s

Create<T>() builds an anonymous T, filling constructor arguments and writable properties. Build<T>().With(...).Create() overrides chosen members once. Freeze<T>() creates a value and makes the fixture return it for every later request. AutoMoqCustomization turns interface requests into Moq mocks.

open as a page

Why do tests built on Bogus data sometimes fail only on the build server, and how do UseSeed and UseDateTimeReference make Faker<T> output repeatable?

level: middleimportance: should knowfreq 35%

basics

~20 s

Bogus draws from a fresh random sequence each run and dates from the current clock, so a rare value can break a test once in fifty runs. UseSeed(int) fixes a Faker<T>'s sequence and UseDateTimeReference fixes its clock, making failures reproducible.

open as a page

What changed in FluentAssertions 8's licence, what does License.Accepted really do, and why do some ASP.NET Core teams move to Shouldly?

level: middleimportance: should knowfreq 40%

basics

~20 s

From version 8 FluentAssertions is under Xceed's licence: free for open-source and non-commercial use, paid for commercial use. License.Accepted = true only suppresses the runtime warning. Teams that will not pay pin 7.x or move to BSD-licensed Shouldly.

open as a page

In an ASP.NET Core 10 unit test, why can't Moq verify logger.LogWarning(...) directly, and what does FakeLogger<T> offer instead?

level: middleimportance: should knowfreq 40%

basics

~10 s

LogWarning is an extension method that calls ILogger.Log<TState>, so Moq rejects it with NotSupportedException. FakeLogger<T> from Microsoft.Extensions.Diagnostics.Testing records each entry as a FakeLogRecord with level, message, exception and structured state to assert on.

open as a page

In .NET 10 unit tests, how do Moq 4.21, NSubstitute 6 and FakeItEasy 9 differ in stubbing a call, checking it happened and answering unconfigured calls?

level: middleimportance: should knowfreq 45%

basics

~10 s

Moq wraps the type: mock.Setup(...).Returns(...) and mock.Verify(..., Times.Once()). NSubstitute calls the substitute itself: sub.Find(...).Returns(...) and sub.Received(1).Find(...). FakeItEasy uses A.CallTo(() => fake.Find(...)).Returns(...) and MustHaveHappenedOnceExactly().

open as a page

Your WebApplicationFactory adds the Testcontainers connection string with ConfigureAppConfiguration, yet the ASP.NET Core 10 app still connects to localhost:5432 — why, and how do you fix it?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Program.cs reads the connection string into a local before builder.Build(), but ConfigureAppConfiguration sources from WebApplicationFactory are applied only at Build. Use builder.UseSetting or ConfigureHostConfiguration instead, which reach the app as command-line arguments before Program.cs runs.

open as a page

In ASP.NET Core database tests, when does a per-test rolled-back transaction work instead of Respawn, and why does it fail through WebApplicationFactory?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Rollback works when the test owns the connection: open it, begin a transaction, attach the DbContext with UseTransaction, and dispose without committing. Through WebApplicationFactory each request uses its own DbContext and pooled connection, so its writes commit outside the test's transaction.

open as a page

With Respawn 7, how do you reset a Testcontainers PostgreSQL database between ASP.NET Core integration tests, and what does ResetAsync actually run?

level: seniorimportance: should knowfreq 38%

basics

~20 s

After migrations, call Respawner.CreateAsync(openConnection, options) once; it reads the tables and foreign keys and builds a delete script. Before each test, ResetAsync(connection) runs it: one TRUNCATE ... CASCADE on PostgreSQL, ordered DELETEs on SQL Server.

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

How do you unit test an ASP.NET Core 10 middleware or filter in a grocery app with DefaultHttpContext, and what does that context leave out?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Build a DefaultHttpContext with the path, headers and services the code reads, pass a lambda as the next RequestDelegate, call InvokeAsync, then assert on status, headers, Items and whether next ran. Replace Response.Body with a MemoryStream to read output.

open as a page

In an ASP.NET Core 10 grocery app, how do you unit test that a coupon expires at midnight by using TimeProvider and FakeTimeProvider?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Make the coupon service read time from an injected TimeProvider, register TimeProvider.System in the app, and in tests pass a FakeTimeProvider set just before midnight; assert the coupon works, Advance past midnight, and assert it is rejected.

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

How do AutoFixture's [AutoData] and [Frozen] parameters work in xUnit theories, and what blocks them when the test project moves to xunit.v3?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

[AutoData] fills every theory parameter from a Fixture, and [Frozen] freezes a parameter so later parameters receive the same instance. AutoFixture 4.18.1's AutoFixture.Xunit2 is built on xUnit v2's data-attribute contract and ships no xunit.v3 package.

open as a page