Verified 2026-09 against https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-10.0, https://dotnet.testcontainers.org/, https://masstransit.io/documentation/concepts/testing, https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.time.testing.faketimeprovider and https://learn.microsoft.com/en-us/dotnet/aspire/testing/write-your-first-test.
The ApiFactory in the skill body is the frame; these are the parts that go inside it.
1. Test authentication handler
Disabling authorisation in tests means the policies are never exercised, so the first production 403 is a surprise. Issue a real identity instead.
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
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()
{
// Each test states who it is by sending headers; no header means anonymous.
if (!Request.Headers.TryGetValue("X-Test-Subject", out var subject))
{
return Task.FromResult(AuthenticateResult.NoResult());
}
var claims = new List<Claim> { new(ClaimTypes.NameIdentifier, subject.ToString()) };
claims.AddRange(Request.Headers["X-Test-Scope"]
.Where(s => !string.IsNullOrEmpty(s))
.Select(s => new Claim("scope", s!)));
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme));
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme)));
}
}
Wire it in ConfigureTestServices:
services.AddAuthentication(TestAuthHandler.Scheme)
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(TestAuthHandler.Scheme, _ => { });
Then a test says who it is, and an anonymous request still gets a real 401:
var client = factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Test-Subject", "user-1");
client.DefaultRequestHeaders.Add("X-Test-Scope", "orders.write");
Keep at least one test with no headers asserting 401, and one with the wrong scope asserting 403.
2. Resetting data between tests
One container per test run, data reset per test. Respawn deletes the rows without dropping the schema, so migrations run once:
using Respawn;
private Respawner _respawner = null!;
// once, after migrations have been applied
await using var connection = new NpgsqlConnection(_db.GetConnectionString());
await connection.OpenAsync();
_respawner = await Respawner.CreateAsync(connection, new RespawnerOptions
{
DbAdapter = DbAdapter.Postgres,
SchemasToInclude = ["orders"],
TablesToIgnore = [new Respawn.Graph.Table("__EFMigrationsHistory")],
});
// before each test
await _respawner.ResetAsync(connection);
The alternatives, in order of preference when Respawn does not fit: a transaction per test rolled back at the end (fails as soon as the code under test manages its own transaction), or a fresh schema per test collection (slower, but total isolation and works with parallel collections).
3. Faking outbound HTTP
For one or two calls, a stub handler is enough and has no dependencies:
public sealed class StubHandler(Func<HttpRequestMessage, HttpResponseMessage> respond)
: HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken) =>
Task.FromResult(respond(request));
}
services.AddHttpClient<PaymentsClient>()
.ConfigurePrimaryHttpMessageHandler(() => new StubHandler(_ =>
new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("""{"status":"authorised"}""", Encoding.UTF8, "application/json"),
}));
For a realistic third-party API — several routes, status codes, latency, recorded responses — use WireMock.Net in a container or in-process, and assert on the requests it received. Either way, make an unexpected outbound call fail the test; a fake that silently returns 200 for everything hides the bug where you called the wrong URL.
4. Message consumers
With MassTransit, the in-memory test harness runs the real consumer with real retry and middleware:
await using var provider = new ServiceCollection()
.AddMassTransitTestHarness(x => x.AddConsumer<OrderPlacedConsumer>())
.BuildServiceProvider(true);
var harness = provider.GetRequiredService<ITestHarness>();
await harness.Start();
await harness.Bus.Publish(new OrderPlaced(OrderId: Guid.NewGuid()));
Assert.True(await harness.Consumed.Any<OrderPlaced>());
Assert.True(await harness.Published.Any<InvoiceRequested>());
The tests worth writing here are the ones messaging-patterns demands: the same message delivered
twice produces one effect, a permanent failure dead-letters instead of retrying forever, and the
outbox row and the state change commit together or not at all.
5. Background services
A BackgroundService registered in the host will start during every integration test and race with
them. Remove it in ConfigureTestServices and test it directly:
services.RemoveAll<IHostedService>(); // or remove the specific registration
using var cts = new CancellationTokenSource();
var worker = new WorkQueueWorker(queue, scopeFactory, NullLogger<WorkQueueWorker>.Instance);
await worker.StartAsync(cts.Token);
await queue.EnqueueAsync((_, _) => ValueTask.CompletedTask, cts.Token);
// poll for the effect with a deadline, then:
await worker.StopAsync(CancellationToken.None);
Poll with a deadline (while (!done && DateTime.UtcNow < deadline)), never Thread.Sleep(500) —
that is the line that makes the suite slow and still flaky on a loaded CI agent.
6. Controlling time
using Microsoft.Extensions.Time.Testing; // Microsoft.Extensions.TimeProvider.Testing
var time = new FakeTimeProvider(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero));
var service = new TrialService(time);
time.Advance(TimeSpan.FromDays(31));
Assert.True(service.IsExpired());
Advance also fires timers created through the provider, which is how you test a retry delay or a
scheduled job without waiting for it. This only works if production code takes TimeProvider by
constructor — a DateTime.UtcNow anywhere in the path makes the test untestable and the failure
looks like flakiness.
7. When Aspire owns the dependencies
If the solution has an Aspire app host, Aspire.Hosting.Testing starts the same graph the developer
runs locally, so the test uses the real Postgres and broker the app host declares instead of a second
Testcontainers definition:
var appHost = await DistributedApplicationTestingBuilder
.CreateAsync<Projects.Acme_AppHost>();
await using var app = await appHost.BuildAsync();
await app.StartAsync();
var client = app.CreateHttpClient("orders-api");
Worth it when the app host already exists and the graph is non-trivial. Not worth introducing an app
host for: start-up is slower than a single container, and it couples the test suite to the
orchestration model (dotnet-architecture → hosting-models.md).