Lesson 78 of 93 · 6 min read · Updated

Replacing Services for Tests: ConfigureTestServices and a Test Authentication Handler

An integration test should run as much of the real application as possible, but some services cannot run in a test: a production database, a third-party API, an identity provider, the wall clock. ConfigureTestServices lets you swap exactly those services and nothing else. This lesson shows how to replace the clock and the authentication scheme in a WebApplicationFactory, and how a small test authentication handler lets you test 401, 403 and 204 responses on a protected endpoint.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. Microsoft.AspNetCore.Mvc.Testing 11.0.0
  4. Microsoft.Extensions.TimeProvider.Testing 11.0.0
  5. FluentAssertions 7.2.2
  6. Docker is not required.

Design Production Code So It Can Be Swapped

Swapping only works if the application gets its dependencies from DI. Look at the relevant registrations in Program.cs:

M09.IntegrationApi/Program.cs

// --- Background service -------------------------------------------------
// The time abstraction comes from DI; in tests it is REPLACED with FakeTimeProvider.
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddScoped<IReservationCleaner, ExpiredReservationCleaner>();
builder.Services.AddSingleton<ReservationCleanupStatus>();
builder.Services.AddHostedService<ReservationCleanupService>();

// --- Authentication / authorization -------------------------------------
builder.Services.AddAuthentication();
builder.Services.AddAuthorizationBuilder()
.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));

The application never calls DateTime.UtcNow. It asks for a TimeProvider. It also does not hard-code an authentication scheme into the endpoints. The endpoint only says it needs the AdminOnly policy, and the policy only says the user needs the Admin role. Where that user comes from is a separate, replaceable concern.

Swapping the Clock and the Authentication Scheme

Inside ConfigureTestServices, the factory removes the production TimeProvider and registers a FakeTimeProvider. It then adds a test authentication scheme and makes it the default.

M09.IntegrationApi.Tests/Infrastructure/BooksApiFactory.cs

// --- Replace the clock ----------------------------------------------
services.RemoveAll<TimeProvider>();
services.AddSingleton<TimeProvider>(Clock);

// --- Replace authentication -----------------------------------------
services
.AddAuthentication(TestAuthHandler.SchemeName)
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
TestAuthHandler.SchemeName, _ => { });

RemoveAll<TimeProvider>() comes from Microsoft.Extensions.DependencyInjection.Extensions. It deletes every existing registration for the type, so there is no doubt about which one wins. Clock is a public property on the factory, which lets tests move time forward with factory.Clock.Advance(...).

AddAuthentication(TestAuthHandler.SchemeName) sets the default scheme. When the authorization middleware needs to know who the user is, it asks this scheme.

The Test Authentication Handler

A production app might use JWT bearer tokens or OpenID Connect. Starting a real identity provider in every test run would be slow and fragile. Instead, the test uses a small handler that reads the roles from a request header and builds a ClaimsPrincipal from them.

M09.IntegrationApi.Tests/Infrastructure/TestAuthHandler.cs

/// <summary>
/// TEST AUTHENTICATION SCHEME
///
/// Starting the production OAuth/OIDC stack to test protected endpoints is
/// both slow and fragile. Instead we use a small scheme that looks at the
/// request headers and produces the requested claims.
///
/// Usage:
/// client.DefaultRequestHeaders.Add("X-Test-Roles", "Admin");
/// </summary>
public sealed class TestAuthHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
public const string SchemeName = "TestScheme";

/// <summary>Without this header the request counts as ANONYMOUS.</summary>
public const string RolesHeader = "X-Test-Roles";

/// <summary>Optional header that sets the user name.</summary>
public const string UserHeader = "X-Test-User";

protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Request.Headers.TryGetValue(RolesHeader, out var roleHeader))
{
// No header means not authenticated → we get 401.
return Task.FromResult(AuthenticateResult.NoResult());
}

var userName = Request.Headers.TryGetValue(UserHeader, out var user)
? user.ToString()
: "test-kullanici";

var claims = new List<Claim> { new(ClaimTypes.Name, userName) };

claims.AddRange(roleHeader.ToString()
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(role => new Claim(ClaimTypes.Role, role)));

var identity = new ClaimsIdentity(claims, SchemeName);
var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), SchemeName);

return Task.FromResult(AuthenticateResult.Success(ticket));
}
}

The handler has two paths. Without the X-Test-Roles header it returns NoResult(), so the request is anonymous. With the header it returns Success with a name claim and one role claim per comma-separated value. The test controls the user simply by setting a header.

NoResult() is the right choice for the missing header. It means "this scheme has nothing to say about the request", which is exactly how an anonymous request looks in production. The authorization middleware then sees an unauthenticated user on a protected endpoint and issues a challenge, which becomes a 401. The optional X-Test-User header is there for endpoints that read the user name, for example to record who changed a row.

Testing 401, 403 and 204

With the handler in place, the three authorization outcomes become three short tests.

M09.IntegrationApi.Tests/HttpPipelineTests.cs

[Fact]
public async Task DeleteBook_WithoutAuthentication_Returns401()
{
// The REAL authorization middleware runs — a unit test could not show this.
var response = await _client.DeleteAsync("/api/books/1");

response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}

[Fact]
public async Task DeleteBook_WithWrongRole_Returns403()
{
using var client = factory.CreateClient();
client.DefaultRequestHeaders.Add(TestAuthHandler.RolesHeader, "Reader");

var response = await client.DeleteAsync("/api/books/1");

response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
}

[Fact]
public async Task DeleteBook_AsAdmin_Returns204()
{
await factory.SeedAsync(new Book
{
Isbn = "978-975-000-003", Title = "Silinecek", Author = "Yazar",
PriceTry = 50m, PublishedYear = 2019,
});

await using var db = factory.CreateDbContext();
var id = db.Books.Single(b => b.Isbn == "978-975-000-003").Id;

using var client = factory.CreateClient();
client.DefaultRequestHeaders.Add(TestAuthHandler.RolesHeader, "Admin");

var response = await client.DeleteAsync($"/api/books/{id}");

response.StatusCode.Should().Be(HttpStatusCode.NoContent);
}

The difference between 401 and 403 is worth testing on purpose. 401 means "I do not know who you are". 403 means "I know who you are, and you are not allowed". A misconfigured policy often turns one into the other, and client code usually reacts differently to each.

Notice that the tests that set a header create their own HttpClient. The shared _client stays anonymous, so a header set in one test cannot leak into another.

What the Test Handler Does Not Test

Replacing authentication is a trade-off, and you should know what you gave up. These tests prove that the endpoint is protected, that the policy requires the Admin role, and that the middleware order is correct. They do not prove that a real token is validated correctly: issuer, audience, signing keys, expiry and claim mapping all belong to the production scheme, which never runs here. If those settings carry risk, cover them with a separate, smaller set of tests that use real tokens, or with an end-to-end test against a real identity provider.

Summary

  1. Ask for dependencies such as TimeProvider through DI so tests can replace them.
  2. In ConfigureTestServices, use RemoveAll<T>() and then register the test double.
  3. A test authentication handler turns a request header into claims, so tests choose the user per request.
  4. Test 401, 403 and the success path separately; they protect different parts of the contract.
  5. A test scheme proves authorization rules, not token validation. Cover token settings elsewhere if they matter.