What you'll learn

A health check can return 200 OK while an important API request flow is broken. A functional test sends a request through the ASP.NET Core pipeline and checks observable behavior across routing, middleware, services, and persistence.

The examples start with a public health endpoint, then add shared test infrastructure and tests for a protected Client endpoint, including a 403 Forbidden authorization check. They target .NET 11 and xUnit v3; replace the sample API types and routes with your own.

Why it matters

A handler can pass unit tests while the running API has a broken service registration, authorization policy, database mapping, or middleware order. A request through the configured host exposes these integration failures.

A health route might return 404, a database write might fail with 500, or a forbidden request might succeed. Database mocks hide provider-specific behavior, and shared mutable rows or WireMock mappings make parallel failures harder to reproduce. Functional tests take longer than unit tests, so focus them on important request behavior and isolate mutable data.

Implementation

1. Set up .NET 11 and xUnit v3

Target both projects at net11.0. Use ASP.NET Core and EF Core 11.0.0, plus a PostgreSQL provider that supports EF Core 11 and has a compatible major version.

The test project uses xUnit v3, ASP.NET Core's test host, Testcontainers, WireMock.NET, and Bogus. For the Microsoft Testing Platform (MTP) runner, merge the root global.json setting below and enable the matching project property. For VSTest, omit both MTP settings and use a current xUnit Visual Studio adapter (3.x) with Microsoft.NET.Test.Sdk. See the MTP overview.

The versions below are placeholders, not a tested package matrix. Choose stable versions compatible with your framework, EF Core, and provider. Testcontainers needs a running Docker-compatible engine. Run dotnet test --project FunctionalTest/FunctionalTest.csproj to execute the project. Omit PostgreSQL or JWT bearer packages and setup if your API does not use them.

XML


<!-- API: include only packages used by the application. -->
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="11.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="11.0.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="<EF-Core-11-compatible-version>" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="11.0.0" />

<!-- Functional-test project: pin compatible stable versions. -->
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="11.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="<current-version>" />
<PackageReference Include="xunit.v3" Version="<current-version>" />
<PackageReference Include="xunit.runner.visualstudio" Version="<3.x-version>" />
<PackageReference Include="Testcontainers.PostgreSql" Version="<current-version>" />
<PackageReference Include="WireMock.Net" Version="<current-version>" />
<PackageReference Include="Bogus" Version="<current-version>" />
            
JSON


{
  "test": {
    "runner": "Microsoft.Testing.Platform"
  }
}
            

An xUnit v3 test project is an executable. Reference the API project and set the target framework, output type, and MTP runner property:

XML


<PropertyGroup>
  <TargetFramework>net11.0</TargetFramework>
  <OutputType>Exe</OutputType>
  <ImplicitUsings>enable</ImplicitUsings>
  <Nullable>enable</Nullable>
  <IsTestProject>true</IsTestProject>
  <UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
</PropertyGroup>
            

2. Test an unauthenticated public health endpoint first

Start with a public route to test routing and the application host without identity or database setup. Use an existing unauthenticated health or ping endpoint, or add a minimal endpoint like this to the sample application. Do not remove authorization from a protected endpoint to make the test pass.

C#


using Microsoft.AspNetCore.Authorization;

app.MapGet("/health", () => Results.Ok(new { status = "Healthy" }))
    .AllowAnonymous();
            

The assertion checks that an unauthenticated request succeeds with the expected status. Match the path and response to your health endpoint's contract. This is an intermediate smoke test; the assembly-fixture section shows how to share the host in the final test assembly.

C#


using Microsoft.AspNetCore.Mvc.Testing;
using System.Net;
using Xunit;

namespace FunctionalTest;

public sealed class HealthTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;

    public HealthTests(WebApplicationFactory<Program> factory) =>
        _factory = factory;

    [Fact]
    public async Task GetHealth_ReturnsOkWithoutAuthentication()
    {
        using var client = _factory.CreateClient();
        using var response = await client.GetAsync(
            "/health", TestContext.Current.CancellationToken);

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }
}
            

3. Share expensive infrastructure with an assembly fixture

Use an xUnit v3 assembly fixture to own the shared application host and external resources. Its asynchronous initialization starts dependencies before the host creates services, and disposal tears them down after testing. Each test still owns its HttpClient, database scope, claims, and mutable records. Once registered, xUnit initializes the fixture for the assembly. Inject AppFixture into the health test and call fixture.CreateClient(), or keep the smoke test in a separate assembly if it must run without containers.

An assembly fixture does not disable xUnit parallel execution. Avoid shared mutable state, use unique rows, and serialize or isolate tests that change shared resources. A WireMock server shared by parallel tests needs concurrency-safe mappings and request assertions.

C#


using Microsoft.AspNetCore.Mvc.Testing;
using System.Net;
using Xunit;

[assembly: AssemblyFixture(typeof(FunctionalTest.AppFixture))]

namespace FunctionalTest;

public sealed class AppFixture : WebApplicationFactory<Program>, IAsyncLifetime
{
    public ValueTask InitializeAsync()
    {
        // Start shared dependencies before the test host uses them.
        return ValueTask.CompletedTask;
    }

    public ValueTask DisposeAsync()
    {
        // Dispose the host and shared dependencies after the tests.
        return ValueTask.CompletedTask;
    }
}

public sealed class HealthTests(AppFixture fixture)
{
    [Fact]
    public async Task GetHealth_ReturnsOkWithoutAuthentication()
    {
        using var client = fixture.CreateClient();
        using var response = await client.GetAsync(
            "/health", TestContext.Current.CancellationToken);

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }
}
            

4. Run the real database in Testcontainers

Testcontainers starts a disposable PostgreSQL container so requests exercise the production provider, not an in-memory substitute. Use the same provider and extensions as production. This example uses pgvector/pgvector:pg16; choose an image with every extension your migrations require.

The example uses separate PostgreSQL databases for the API and Identity because Identity stores the Client record. If your application uses one database, remove the Identity container, connection-string override, test-owned Identity provider and scope, and the Identity migration and assertion shown later.

C#


private readonly PostgreSqlContainer _database =
    new PostgreSqlBuilder("pgvector/pgvector:pg16")
        .WithDatabase("functional_tests")
        .WithUsername("postgres")
        .WithPassword("postgres")
        .Build();

await _database.StartAsync(cancellationToken);
var connectionString = _database.GetConnectionString();
            

5. Apply migrations and seed stable prerequisites

After the container starts, apply migrations and seed only deterministic lookup rows that requests need. Keep shared seed data read-only; let each test create its own entities. EF migrations do not populate Identity users, roles, or other application prerequisites, so call your Identity initializer when needed.

C#


using API.Data;

namespace FunctionalTest;

internal static class DatabaseSeeder
{
    public static async Task SeedAsync(
        AppDbContext db, CancellationToken cancellationToken)
    {
        // Add deterministic reference data required by handlers, if any.
        // Example: db.ClientTypes.Add(new ClientType { Name = "Standard" });
        await db.SaveChangesAsync(cancellationToken);
    }
}
            

Run the migration and seeder after the container starts and before requests reach the host:

C#


await using var scope = Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.MigrateAsync(cancellationToken);
await DatabaseSeeder.SeedAsync(db, cancellationToken);
            

6. Control outbound HTTP with WireMock

WireMock lets the API's configured HTTP client call a controlled partner endpoint. Stub a stable response during fixture initialization, then verify the request when the partner call is part of the behavior under test.

A shared method and path can match another parallel test's request. Include a unique value per test and verify it in the WireMock request log. Isolate or serialize tests that modify shared mappings; the assembly fixture does not make WireMock state thread-safe.

C#


var partnerApi = WireMockServer.Start();
partnerApi.Given(Request.Create()
        .WithPath("/partner/clients")
        .UsingPost())
    .RespondWith(Response.Create()
        .WithStatusCode(201)
        .WithHeader("Content-Type", "application/json")
        .WithBody("{\"id\":\"test-partner-client\"}"));
            

7. Generate unique test data with Bogus

Use Bogus for per-test entities and deterministic data for prerequisite lookups. The fixture's ClientCommand factory adds a random suffix to each name to prevent collisions in parallel persistence tests.

C#


var clientCommand = new Faker<CreateClientCommand>().RuleFor(
    command => command.Name,
    faker => $"{faker.Company.CompanyName()}-"
        + faker.Random.AlphaNumeric(8));

var command = clientCommand.Generate();
            

8. Add a base test and focused HTTP extensions

A base test can expose the fixture, a default client, and a test-owned Identity scope. HTTP extensions centralize response disposal, status assertions, cancellation, and body diagnostics without hiding the behavior under test.

C#


using API.Identity; // Replace with your Identity context namespace.
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using System.Net;
using System.Net.Http.Json;
using Xunit;

namespace FunctionalTest;

public abstract class BaseTest(AppFixture fixture) : IDisposable
{
    private readonly IServiceScope _identityScope = fixture.CreateIdentityScope();
    private readonly HttpClient _client = fixture.CreateClient();

    protected AppFixture Fixture { get; } = fixture;
    protected HttpClient Client => _client;
    protected WebApplicationFactory<Program> Factory => Fixture;
    protected IdentityDbContext IdentityDatabase =>
        _identityScope.ServiceProvider.GetRequiredService<IdentityDbContext>();

    public void Dispose()
    {
        _client.Dispose();
        _identityScope.Dispose();
    }
}

internal static class HttpClientExtensions
{
    public static async Task<TResponse> PostForJsonResultAsync<TResponse>(
        this HttpClient client, string path, object request,
        HttpStatusCode expectedStatus, ITestOutputHelper output)
    {
        using var response = await client.PostAsJsonAsync(
            path, request, TestContext.Current.CancellationToken);
        if (response.StatusCode != expectedStatus)
            output.WriteLine(await response.Content.ReadAsStringAsync(
                TestContext.Current.CancellationToken));

        Assert.Equal(expectedStatus, response.StatusCode);
        var result = await response.Content.ReadFromJsonAsync<TResponse>(
            cancellationToken: TestContext.Current.CancellationToken);
        Assert.NotNull(result);
        return result;
    }

    public static async Task PostAsync(
        this HttpClient client, string path, object request,
        HttpStatusCode expectedStatus)
    {
        using var response = await client.PostAsJsonAsync(
            path, request, TestContext.Current.CancellationToken);
        Assert.Equal(expectedStatus, response.StatusCode);
    }
}
            

Use WireMock for outbound HTTP so the real client, serialization, and request configuration still run. For an irrelevant non-HTTP dependency, replace only that registration with a focused fake in the fixture below. Keep the database real when testing database integration.

9. Define production authentication and the Client authorization policy

Keep real authentication and authorization in the API. This JWT bearer example validates configured issuer and audience values; use your application's settings and policies. The Client policy requires the lowercase role=master claim, avoiding reliance on framework role-name mapping.

C#


using Microsoft.AspNetCore.Authentication.JwtBearer;

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = builder.Configuration["Jwt:Authority"];
        options.Audience = builder.Configuration["Jwt:Audience"];
    });

builder.Services.AddAuthorization(options =>
    options.AddPolicy("ManageClients", policy =>
        policy.RequireClaim("role", "master")));

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

Protect the Client action with [Authorize(Policy = "ManageClients")]. The test-only handler does not validate JWT signatures, issuer, audience, or expiration; use real test tokens in separate tests for those checks.

10. Replace authentication only inside the test host

A test authentication scheme gives each client an identity without minting production tokens. The master identity carries role=master; the theory tests authenticated role=owner, role=manager, and role=cashier identities. Claims are lowercase, and the identity sets RoleClaimType = "role".

Pass claims per client in a request header instead of changing shared DefaultRequestHeaders. A malformed header fails authentication rather than falling back to the fixture's elevated default identity.

C#


using System.Security.Claims;
using Xunit;

namespace FunctionalTest;

internal sealed record ClaimDto(string Type, string Value);

public sealed class AuthClaimsProvider(IList<Claim> claims)
{
    public const string RoleClaimType = "role";
    public IList<Claim> Claims { get; } = claims;

    public static AuthClaimsProvider WithMasterClaims() => new(
    [
        new Claim(ClaimTypes.NameIdentifier, "functional-test-master"),
        new Claim(ClaimTypes.Name, "Test Master"),
        new Claim(RoleClaimType, "master")
    ]);

    public static AuthClaimsProvider WithRole(string role) => new(
    [
        new Claim(ClaimTypes.NameIdentifier, "functional-test-user"),
        new Claim(RoleClaimType, role)
    ]);
}

public sealed class ClaimsBelowMasterClaim : TheoryData<AuthClaimsProvider>
{
    public ClaimsBelowMasterClaim()
    {
        Add(AuthClaimsProvider.WithRole("owner"));
        Add(AuthClaimsProvider.WithRole("manager"));
        Add(AuthClaimsProvider.WithRole("cashier"));
    }
}
            

Without a claims header, the handler uses fixture defaults. The parser accepts only valid Base64 JSON claims, and the delegating handler adds the selected claims to each request from that client.

C#


using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;

namespace FunctionalTest;

public sealed class TestAuthHandler(
    IOptionsMonitor<AuthenticationSchemeOptions> options,
    ILoggerFactory logger, UrlEncoder encoder, AuthClaimsProvider defaults)
    : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
    public const string SchemeName = "Test";
    public const string ClaimsHeader = "X-Test-Claims";

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        IList<Claim> claims = defaults.Claims;
        if (Request.Headers.TryGetValue(ClaimsHeader, out var header))
        {
            try
            {
                claims = TestClaimsParser.ReadHeaderClaims(header.ToString());
            }
            catch (FormatException) { return Fail("Claims header must be Base64 encoded."); }
            catch (JsonException) { return Fail("Claims header must contain valid JSON."); }
        }

        var identity = new ClaimsIdentity(
            claims, SchemeName, ClaimTypes.Name, AuthClaimsProvider.RoleClaimType);
        var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), SchemeName);
        return Task.FromResult(AuthenticateResult.Success(ticket));
    }

    private static Task<AuthenticateResult> Fail(string message) =>
        Task.FromResult(AuthenticateResult.Fail(message));
}

internal static class TestClaimsParser
{
    public static IList<Claim> ReadHeaderClaims(string header)
    {
        var json = Encoding.UTF8.GetString(Convert.FromBase64String(header));
        var values = JsonSerializer.Deserialize<ClaimDto[]>(json);
        if (values is null || values.Any(value =>
            value is null || string.IsNullOrWhiteSpace(value.Type) || value.Value is null))
            throw new JsonException("Invalid test claims.");

        return values.Select(value => new Claim(value.Type, value.Value)).ToList();
    }
}

internal sealed class ClaimsInjectionHandler(IList<Claim> claims) : DelegatingHandler
{
    private readonly string _header = Convert.ToBase64String(Encoding.UTF8.GetBytes(
        JsonSerializer.Serialize(claims.Select(
            claim => new ClaimDto(claim.Type, claim.Value)))));

    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.Headers.Remove(TestAuthHandler.ClaimsHeader);
        request.Headers.TryAddWithoutValidation(TestAuthHandler.ClaimsHeader, _header);
        return base.SendAsync(request, cancellationToken);
    }
}

public static class TestClientExtensions
{
    public static HttpClient CreateClientWithClaims(
        this WebApplicationFactory<Program> factory, AuthClaimsProvider claims) =>
        factory.CreateDefaultClient(new ClaimsInjectionHandler(claims.Claims));
}
            

Register this handler only in the functional-test host. It establishes a test identity, not a production bearer token. Changing default schemes does not replace one explicitly named by an [Authorize(AuthenticationSchemes = "...")] attribute or policy. Configure those endpoints to use a compatible test scheme and policy, or use real test tokens; otherwise the named production handler still processes requests. Add required tenant or other claims, and create a client for each claims set.

11. Assemble the shared AppFixture

This fixture combines the assembly lifecycle, Testcontainers databases, WireMock partner, and migration and seed setup before starting the web host. This keeps database-dependent hosted services from starting against an unmigrated schema. Replace the sample contexts, connection-string keys, and seed logic with your API's equivalents, and include any additional DbContext configuration your app needs.

The service-registration placeholder is optional. Replace a production service with a focused fake only when the service is outside the behavior under test. If your app has one database, remove the Identity container and its test-owned services as described above.

C#


using API.Data;
using API.Identity; // Replace with your Identity context namespace.
using Bogus;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Shared.Features.Clients;
using Testcontainers.PostgreSql;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
using Xunit;

[assembly: AssemblyFixture(typeof(FunctionalTest.AppFixture))]
namespace FunctionalTest;

public sealed class AppFixture : WebApplicationFactory<Program>, IAsyncLifetime
{
    private readonly PostgreSqlContainer _database =
        new PostgreSqlBuilder("pgvector/pgvector:pg16")
            .WithDatabase("functional_tests")
            .WithUsername("postgres").WithPassword("postgres").Build();
    private readonly PostgreSqlContainer _identityDatabase =
        new PostgreSqlBuilder("pgvector/pgvector:pg16")
            .WithDatabase("identity_tests")
            .WithUsername("postgres").WithPassword("postgres").Build();
    private readonly WireMockServer _partnerApi = WireMockServer.Start();
    private ServiceProvider? _identityServices;

    public WireMockServer PartnerApi => _partnerApi;
    public Faker<CreateClientCommand> ClientCommand =>
        new Faker<CreateClientCommand>().RuleFor(
            command => command.Name,
            faker => $"{faker.Company.CompanyName()}-{faker.Random.AlphaNumeric(8)}");

    internal IServiceScope CreateIdentityScope() =>
        (_identityServices ?? throw new InvalidOperationException(
            "Fixture is not initialized.")).CreateScope();

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.UseEnvironment("Test");
        builder.ConfigureAppConfiguration((_, config) =>
            config.AddInMemoryCollection(new Dictionary<string, string?>
            {
                ["PartnerApi:BaseUrl"] = _partnerApi.Url,
                ["ConnectionStrings:Identity"] = _identityDatabase.GetConnectionString()
            }));
        builder.ConfigureTestServices(services =>
        {
            services.RemoveAll<AppDbContext>();
            services.RemoveAll<DbContextOptions<AppDbContext>>();
            services.RemoveAll<IDbContextOptionsConfiguration<AppDbContext>>();
            services.AddDbContext<AppDbContext>(options =>
                options.UseNpgsql(_database.GetConnectionString()));

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = TestAuthHandler.SchemeName;
                options.DefaultAuthenticateScheme = TestAuthHandler.SchemeName;
                options.DefaultChallengeScheme = TestAuthHandler.SchemeName;
                options.DefaultForbidScheme = TestAuthHandler.SchemeName;
            }).AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
                TestAuthHandler.SchemeName, _ => { });
            services.AddScoped(_ => AuthClaimsProvider.WithMasterClaims());

            // Optional: replace a production service with a focused fake.
            // services.RemoveAll<IYourService>();
            // services.AddScoped<IYourService, FakeYourService>();
        });
    }

    public async ValueTask InitializeAsync()
    {
        var cancellationToken = TestContext.Current.CancellationToken;
        await _database.StartAsync(cancellationToken);
        await _identityDatabase.StartAsync(cancellationToken);
        _partnerApi.Given(Request.Create().WithPath("/partner/clients").UsingPost())
            .RespondWith(Response.Create().WithStatusCode(201)
                .WithHeader("Content-Type", "application/json")
                .WithBody("{\"id\":\"test-partner-client\"}"));

        var identityServices = new ServiceCollection();
        identityServices.AddDbContext<IdentityDbContext>(options =>
            options.UseNpgsql(_identityDatabase.GetConnectionString()));
        _identityServices = identityServices.BuildServiceProvider();
        await using (var identityScope = _identityServices.CreateAsyncScope())
        {
            var identityDb = identityScope.ServiceProvider
                .GetRequiredService<IdentityDbContext>();
            await identityDb.Database.MigrateAsync(cancellationToken);
            // Run your Identity initializer here if lookup/prerequisite data is needed.
        }

        var appDbServices = new ServiceCollection();
        appDbServices.AddDbContext<AppDbContext>(options =>
            options.UseNpgsql(_database.GetConnectionString()));
        await using var appDbProvider = appDbServices.BuildServiceProvider();
        await using var appDbScope = appDbProvider.CreateAsyncScope();
        var db = appDbScope.ServiceProvider.GetRequiredService<AppDbContext>();
        await db.Database.MigrateAsync(cancellationToken);
        await DatabaseSeeder.SeedAsync(db, cancellationToken);
    }

    public override async ValueTask DisposeAsync()
    {
        await base.DisposeAsync();
        await _database.DisposeAsync();
        if (_identityServices is not null)
            await _identityServices.DisposeAsync();
        await _identityDatabase.DisposeAsync();
        _partnerApi.Dispose();
    }
}
            

12. Test Client persistence and reject lower roles

This sample creates a Client as a master user and verifies the row in the Identity database. Adapt its command, DTO, context, and route to your API, then verify authenticated lower-role users receive 403 Forbidden.

C#


using Microsoft.EntityFrameworkCore;
using Shared.Features.Clients;
using System.Net;
using Xunit;

namespace FunctionalTest;

public sealed class ClientTests(AppFixture fixture, ITestOutputHelper output)
    : BaseTest(fixture)
{
    [Fact]
    public async Task Create_ReturnsAndPersistsClient()
    {
        var command = Fixture.ClientCommand.Generate();
        var result = await Client.PostForJsonResultAsync<ClientDto>(
            "/api/clients", command, HttpStatusCode.Created, output);

        Assert.Equal(command.Name, result.Name);
        Assert.True(result.Active);

        var saved = await IdentityDatabase.Clients.FirstAsync(
            client => client.Name == result.Name,
            TestContext.Current.CancellationToken);
        Assert.Equal(result.Name, saved.Name);
        Assert.True(saved.Active);
    }

    [Theory]
    [ClassData(typeof(ClaimsBelowMasterClaim))]
    public async Task Create_Returns_ForbiddenResponse(AuthClaimsProvider claims)
    {
        using var client = Factory.CreateClientWithClaims(claims);
        await client.PostAsync(
            "/api/clients", Fixture.ClientCommand.Generate(),
            HttpStatusCode.Forbidden);
    }
}
            

The forbidden theory's identities authenticate but lack the exact role=master claim. Keep records unique across parallel tests, and isolate or serialize tests that mutate shared WireMock mappings.

Summary

  • Start with a public health or ping endpoint and assert its observable response without authentication.
  • Use an assembly fixture for shared host resources, but keep clients, scopes, claims, and mutable data test-local.
  • Use Testcontainers for real database-provider behavior, WireMock for controlled outbound HTTP, and Bogus for unique request data.
  • Keep production authentication intact; use per-client test claims to verify both permitted and forbidden behavior.

What to read next: learn how to test an ASP.NET Web API with HTTP REPL and HTTP files, or review JWT bearer authentication in ASP.NET Web API.