Lesson 78 of 93 · 6 min read · Updated
Replacing Services for Tests: ConfigureTestServices and a Test Authentication Handler
On this page
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
- .NET 11 SDK
- xUnit 2.9.3
Microsoft.AspNetCore.Mvc.Testing11.0.0Microsoft.Extensions.TimeProvider.Testing11.0.0- FluentAssertions 7.2.2
- 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
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
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
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
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
- Ask for dependencies such as
TimeProviderthrough DI so tests can replace them. - In
ConfigureTestServices, useRemoveAll<T>()and then register the test double. - A test authentication handler turns a request header into claims, so tests choose the user per request.
- Test 401, 403 and the success path separately; they protect different parts of the contract.
- A test scheme proves authorization rules, not token validation. Cover token settings elsewhere if they matter.