📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you test an ASP.NET Core API in memory with WebApplicationFactory? Show how you replace services for a test, handle authentication so protected endpoints can be called, and keep tests isolated from each other.

Covers WebApplicationFactory and TestServer: bootstrapping Program, ConfigureTestServices to swap dependencies, a test authentication handler for protected endpoints, per-test configuration, isolation and what in-memory tests do and do not prove.

Mid-Level Coding Intermediate aspnet-core authentication integration-testing testing webapplicationfactory xunit

🎯 Key points

  • WebApplicationFactory<Program> from Microsoft.AspNetCore.Mvc.Testing boots the real Program with TestServer (no sockets)
  • ConfigureTestServices runs after the app's registrations, so RemoveAll + Add replaces a service
  • A test AuthenticationHandler (scheme "Test") issues claims so [Authorize] endpoints can be exercised
  • Override configuration with UseSetting or ConfigureAppConfiguration and UseEnvironment("Testing")
  • Share one factory per class via IClassFixture; isolate data per test, not per factory
  • Fake only the boundaries you don't own (payment, email, time); keep the real pipeline, routing, validation and DI
  • TestServer is fastest but skips Kestrel limits, TLS and the network; .NET 10's UseKestrel() starts a real server when browser (Playwright) or protocol behaviour matters, at the cost of a real port and slower start

⏱ 30-second answer

WebApplicationFactory<Program> (package Microsoft.AspNetCore.Mvc.Testing) starts your real Program, with its middleware, routing, model binding, filters and DI, on an in-memory TestServer. CreateClient() returns an HttpClient that calls it without opening a socket.

  • Replace services in ConfigureWebHost with builder.ConfigureTestServices(s => { s.RemoveAll<IPaymentGateway>(); s.AddSingleton<IPaymentGateway, FakeGateway>(); }). It runs after the app's own registrations, so the last one wins.
  • Authentication: register a test AuthenticationHandler under a "Test" scheme that builds a ClaimsPrincipal from a header, so [Authorize] and policies run for real.
  • Isolation: one factory per class (IClassFixture), with unique or reset data per test.

The trade-off: very high confidence in the HTTP contract for millisecond-level cost, but no real Kestrel, TLS or network.

🗣 Full answer (senior)

How I would answer this in an interview

"WebApplicationFactory<TEntryPoint> boots the application exactly the way production does: it runs Program, builds the host and swaps Kestrel for TestServer, an in-memory server that turns an HttpRequestMessage straight into an HttpContext. So when I call client.PostAsJsonAsync("/orders", dto) I'm exercising routing, model binding, validation, filters, authorisation, my handler, serialisation and ProblemDetails, all in a few milliseconds, with no port and no network.

To control dependencies I subclass the factory and override ConfigureWebHost. ConfigureTestServices runs after the app's own ConfigureServices, so I RemoveAll<IPaymentGateway>() and add a fake, and I point the DbContext at a Testcontainers SQL Server rather than swapping it for the in-memory provider. For authentication I don't turn it off; I register a small AuthenticationHandler under a "Test" scheme that reads a header like X-Test-User and builds claims. That way [Authorize(Policy = \"CanRefund\")] still runs, and I can write a test proving that a user without the claim gets a 403. For example, at [company] we [had an endpoint whose policy was accidentally removed in a refactor]; a test exactly like that caught it [in the PR].

For isolation I share one factory per test class with IClassFixture, because building the host costs a few hundred milliseconds, and isolate data instead: each test creates its own customer with a unique id, or I reset with Respawn. The mistake I see is replacing so much that the test only proves the fakes work, or using AllowAnonymous everywhere so security is never tested. Fake the edges you don't own, keep everything else real."


The moving parts

Piece What it does
WebApplicationFactory<Program> Finds the entry point, builds the host, swaps in TestServer
ConfigureWebHost(IWebHostBuilder) Your hook: environment, settings, test services
ConfigureTestServices Runs after app registrations, so replacements win
UseSetting(key, value) Overrides configuration (connection strings, feature flags)
CreateClient(options) HttpClient wired to TestServer; set AllowAutoRedirect, BaseAddress
WithWebHostBuilder(...) Derived factory for one test's special setup
Services Root provider; create a scope to seed or inspect data

What to fake and what to keep real

Keep real Fake or replace
Middleware, routing, model binding, validation Third-party HTTP APIs (WireMock.Net)
Authorisation policies Authentication handler (test scheme)
EF Core and SQL (Testcontainers) TimeProvider (FakeTimeProvider)
Serialisation and ProblemDetails Email, SMS, payment gateways

Production example

An orders API had 1,100 unit tests but kept breaking its contract: a renamed property, a missing [FromBody], a 500 instead of a 400 for bad input. Adding 85 WebApplicationFactory tests against a Testcontainers SQL Server added 40 seconds to CI and caught 9 contract regressions in the next quarter before they reached the mobile team.

🔍 What the interviewer is checking

Checks whether the candidate can write realistic in-memory API tests and knows how DI overrides, authentication and isolation work under the hood.

Green flags

  • Explains TestServer and that the real Program and pipeline run
  • Uses ConfigureTestServices with RemoveAll and knows why it wins
  • Tests authorisation with a test scheme instead of disabling it
  • Shares the factory and isolates data per test

Red flags

  • Disables auth or uses the in-memory EF provider without caveats
  • New factory per test, or unaware of singleton leakage
  • Thinks in-memory tests prove the deployed system works

📚 Learn in depth

1. How the factory boots your app

WebApplicationFactory<Program>
   |
   |-- finds Program's assembly, sets content root
   |-- HostFactoryResolver intercepts WebApplication.CreateBuilder(args)
   |       (your Program runs until app.Run())
   |-- applies ConfigureWebHost overrides
   |-- replaces IServer (Kestrel) with TestServer
   v
HttpClient --> TestServer handler --> HttpContext --> your middleware pipeline

The factory uses a diagnostic listener to catch the host when Build() is called, applies your overrides, then stops Program before Run() blocks. That's why Program must be reachable: with top-level statements older versions needed public partial class Program { }. The .NET 10 web SDK generates that declaration for you.

2. Why ConfigureTestServices wins

DI registrations are a list; resolving a single service returns the last registration. ConfigureTestServices callbacks run after the application's builder.Services calls, so anything you add there is last. RemoveAll<T>() is still worth calling, because IEnumerable<T> resolution would otherwise return both.

3. TestServer versus Kestrel

TestServer creates an in-memory HttpMessageHandler. Requests never hit a socket, so there's no TLS, HTTP/2 negotiation, connection limits, ForwardedHeaders from a real proxy or request size limits enforced by Kestrel. .NET 10 adds UseKestrel() on the factory to start a real Kestrel server for tests that need a real port, such as Playwright browser tests.

4. Test authentication

Authentication is pluggable: AddAuthentication("Test").AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("Test", _ => { }). The handler's HandleAuthenticateAsync returns AuthenticateResult.Success(ticket) with the claims you want, or NoResult() to simulate an anonymous caller. Policies, roles and resource-based handlers then run for real. Setting it as the default scheme in ConfigureTestServices means [Authorize] uses it without changing production code.

5. Lifetime and cost

Building the host takes roughly 200 to 800 ms depending on the app. Sharing a factory across a class (or a collection) amortises that. Each CreateClient() is cheap. Because the root IServiceProvider is shared, singletons (caches, in-memory stores) leak between tests in the same factory: reset them or create a derived factory with WithWebHostBuilder.

Try it yourself

  1. Write a test that POSTs invalid JSON and asserts a 400 with a ProblemDetails errors dictionary.
  2. Add a test auth handler and assert that an endpoint with a policy returns 401 anonymous, 403 without the claim and 200 with it.
  3. Replace TimeProvider with FakeTimeProvider and test an endpoint whose output depends on the date.
  4. Time host start-up with one factory per test versus IClassFixture across 50 tests.
  5. Register a singleton in-memory cache, populate it in one test and see it leak into the next; then fix it.

💻 Code

An orders endpoint with a policy, and xUnit v3 tests using a custom factory with a fake gateway and a test authentication scheme:

// Program.cs (code under test, abbreviated)
using Microsoft.AspNetCore.Authorization;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("CanRefund", p => p.RequireClaim("permission", "orders.refund"));
builder.Services.AddSingleton<IPaymentGateway, StripeGateway>();
builder.Services.AddProblemDetails();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

app.MapPost("/orders/{id:int}/refund", async (int id, IPaymentGateway gateway, CancellationToken ct) =>
        await gateway.RefundAsync(id, ct) ? Results.NoContent() : Results.Problem(statusCode: 409))
   .RequireAuthorization("CanRefund");

app.Run();

public interface IPaymentGateway { Task<bool> RefundAsync(int orderId, CancellationToken ct); }
public sealed class StripeGateway : IPaymentGateway
{
    public Task<bool> RefundAsync(int orderId, CancellationToken ct) => throw new NotSupportedException("Real call");
}
// ApiFactory.cs + RefundTests.cs (xunit.v3, Microsoft.AspNetCore.Mvc.Testing)
using System.Net;
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Xunit;

namespace Orders.Api.Tests;

public sealed class FakeGateway : IPaymentGateway
{
    public List<int> Refunded { get; } = [];
    public Task<bool> RefundAsync(int orderId, CancellationToken ct) { Refunded.Add(orderId); return Task.FromResult(true); }
}

// Builds a principal from the X-Test-Permissions header; no header = anonymous.
public sealed class TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder)
    : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
    public const string Scheme = "Test";

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        if (!Request.Headers.TryGetValue("X-Test-Permissions", out var perms)) return Task.FromResult(AuthenticateResult.NoResult());

        var claims = perms.ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)
            .Select(p => new Claim("permission", p))
            .Append(new Claim(ClaimTypes.NameIdentifier, "test-user"));
        var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme));
        return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme)));
    }
}

public sealed class ApiFactory : WebApplicationFactory<Program>
{
    public FakeGateway Gateway { get; } = new();

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.UseEnvironment("Testing");
        builder.ConfigureTestServices(services =>
        {
            // Runs after Program's registrations, so these replace the real ones.
            services.RemoveAll<IPaymentGateway>();
            services.AddSingleton<IPaymentGateway>(Gateway);

            services.AddAuthentication(TestAuthHandler.Scheme)
                    .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(TestAuthHandler.Scheme, _ => { });
        });
    }
}

public sealed class RefundTests(ApiFactory factory) : IClassFixture<ApiFactory>
{
    private HttpClient ClientWith(string? permissions)
    {
        var client = factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });
        if (permissions is not null) client.DefaultRequestHeaders.Add("X-Test-Permissions", permissions);
        return client;
    }

    [Fact]
    public async Task Anonymous_caller_gets_401() =>
        Assert.Equal(HttpStatusCode.Unauthorized,
            (await ClientWith(null).PostAsync("/orders/7/refund", null, TestContext.Current.CancellationToken)).StatusCode);

    [Fact]
    public async Task Caller_without_permission_gets_403() =>
        Assert.Equal(HttpStatusCode.Forbidden,
            (await ClientWith("orders.read").PostAsync("/orders/7/refund", null, TestContext.Current.CancellationToken)).StatusCode);

    [Fact]
    public async Task Caller_with_permission_refunds_through_gateway()
    {
        var response = await ClientWith("orders.refund").PostAsync("/orders/8/refund", null, TestContext.Current.CancellationToken);

        Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
        Assert.Contains(8, factory.Gateway.Refunded);
    }
}

⚠ Common mistakes

  • Mistake: Disabling authorisation in tests (AllowAnonymous, a policy that always succeeds). Why it is wrong: Security rules are never tested and a removed policy goes unnoticed. Instead: Use a test authentication scheme and assert 401, 403 and 200 cases.
  • Mistake: Swapping the DbContext for the EF Core in-memory provider. Why it is wrong: No SQL translation, constraints, transactions or concurrency, so tests pass on queries that fail in SQL Server. Instead: Use Testcontainers SQL Server or at least SQLite, and reset data with Respawn.
  • Mistake: Creating a new factory in every test. Why it is wrong: Host start-up costs hundreds of milliseconds per test. Instead: Share it with IClassFixture or a collection fixture and isolate data.
  • Mistake: Adding a fake without removing the real registration. Why it is wrong: Consumers of IEnumerable<T> get both, and decorators may wrap the wrong one. Instead: RemoveAll<T>() before adding the replacement.
  • Mistake: Assuming singleton state resets between tests. Why it is wrong: The factory's root provider lives as long as the factory, so caches and fakes carry state. Instead: Reset fakes in the test constructor or use WithWebHostBuilder for a fresh host.
  • Mistake: Asserting only on status codes. Why it is wrong: The JSON contract (property names, casing, null handling) is what clients depend on. Instead: Deserialise and assert key fields, or snapshot the body with Verify.
  • Mistake: Treating in-memory tests as proof the deployment works. Why it is wrong: TestServer skips Kestrel, TLS, reverse proxies and real configuration sources. Instead: Add a small smoke test suite against the deployed environment.

🏛 Senior insight: trade-offs

WebApplicationFactory tests are usually the best value tests in an API: they cover the HTTP contract, DI wiring, validation and security with almost no flakiness. I aim for every endpoint to have at least a happy path, a validation failure and an authorisation failure at this level, and keep unit tests for complex domain logic only.

Option When it fits Cost When not to
WebApplicationFactory + TestServer Contract, wiring, security of an API Host start per factory, in-memory only Testing TLS, proxies, HTTP/2 specifics
WebApplicationFactory + UseKestrel (.NET 10) Browser tests with Playwright Real port, slower Plain API contract tests
Deployed smoke tests Proving the release works Environment needed Broad behaviour coverage
Unit tests of handlers Complex rules with many cases Miss pipeline and binding Simple CRUD endpoints

Measure suite time per test and failure causes: if most failures come from fakes being wrong, you are faking too much.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate talks about what to include in integration tests. Why: Checks the wider strategy for real versus fake dependencies.
    How to answer

    Use WebApplicationFactory<Program> to start the real app in memory and send real HTTP requests through the whole pipeline: middleware, routing, model binding, validation, DI, authorisation and JSON. Run the things you own for real, including EF Core against a real SQL Server in Testcontainers, because that is where mapping, translation and migration bugs live. Fake the things you don't own: third-party HTTP APIs (WireMock.Net), email and SMS, the clock (FakeTimeProvider), and usually the identity provider via a test authentication handler. Keep tests isolated by resetting data between tests with Respawn and sharing one container per test collection. The trade-off is a few seconds of start-up for far more confidence than mocks give.

  2. When: Candidate mentions replacing the DbContext. Why: Checks practical wiring of real infrastructure into in-memory API tests.
    How to answer

    Derive a factory from WebApplicationFactory<Program> and implement IAsyncLifetime. InitializeAsync starts an MsSqlContainer, and DisposeAsync disposes the container and then the factory. In ConfigureWebHost, point the app at the container with UseSetting("ConnectionStrings:Orders", ...). You can also swap the DbContext registration in ConfigureTestServices.

    Run EF Core migrations once per fixture, so the tests use the real schema. Then reset rows before each test with Respawn, which deletes data in foreign-key order and keeps the schema.

    Use it as an IClassFixture and every class gets its own database. For speed, share one container and give each class a unique database name. The trade-off is that real SQL Server catches what in-memory providers hide (constraints, transactions, SQL translation), at the price of Docker and a few seconds of start-up.

🛠 Real-world problems: how you handle them

Refund endpoint lost its authorisation policy in a refactor
Situation
An orders API on [Azure App Service] serving [the customer support portal]; a refactor moved endpoints from controllers to Minimal API route groups. Refunds of up to [A$5,000] could be issued.
Signals
No alerts; code review missed it. A security review [weeks later] found that any authenticated support user, not only team leads, could call POST /orders/{id}/refund. Audit logs showed [N] refunds by users without the permission.
Investigation
Diffed the route registrations: the old controller had [Authorize(Policy = "CanRefund")], the new route group only had RequireAuthorization(). The existing integration tests disabled authentication with a permissive handler, so they passed. Checked the test suite and found no test asserting 403 for any endpoint.
Resolution
Immediately added .RequireAuthorization("CanRefund") and deployed. Then replaced the permissive handler with a header-driven TestAuthHandler and added a data-driven test per protected endpoint asserting 401 anonymous, 403 without the permission and 2xx with it.
Prevention
A test enumerates EndpointDataSource and fails if any non-health endpoint lacks authorisation metadata; PR checklist item for policy changes; the authorisation matrix lives next to the tests.

How to tell it (STAR)

**S:** At [company] we moved our orders API from controllers to Minimal APIs, and a security review later found the refund endpoint had lost its policy. **T:** I owned fixing it and making sure it couldn't happen again. **A:** I restored the policy the same day, then found the root cause in our tests: they turned authentication off. I wrote a test authentication handler driven by a header, added 401/403/200 tests for every protected endpoint, and a test that fails if any endpoint has no authorisation metadata. **R:** We covered [42] endpoints in two days, the suite caught [2] more policy mistakes in the following quarter, and refunds by unauthorised users dropped to zero.

↩ Usually asked after

More in .NET Testing Tools

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me