Module 1 · HTTP contracts and realistic test boundaries · Lesson 1 of 12
Build an HTTP contract test that can catch a real regression
Lesson video
Start with a failure the customer can observe
Suppose POST /orders must reject a quantity of zero, create one order for a valid request, return its identifier, and expose that order through GET /orders/{id}. A test that only asserts a controller method was called cannot establish this contract.
Start with the response and persistence assertions below, then assemble the runnable OrdersApi and test project using the supplied manifests. The factory lesson supplies OrdersFactory and its controlled dependencies.
Write a behavior table before choosing test helpers:
- Valid request: expected status, response schema and one persisted order.
- Invalid quantity: validation response and no persisted order.
- Unknown product: agreed error response and no order.
- Duplicate idempotency key: agreed replay behavior and no second order.
- Unauthorized caller: denied access and no state change.
The exact HTTP status codes belong to your API contract. Do not copy a status code from a tutorial without deciding what it means for your service.
The complete first lab implements valid creation, invalid quantity, an anonymous denial and sequential replay. Unknown-product handling is a design extension: the default pricing stub returns 2.50 for any SKU, so these four tests do not establish that branch.
Use the application pipeline
WebApplicationFactory can start the application under a test host and provide an HttpClient. This exercises routing, middleware, binding and serialization as well as endpoint logic. The test project references the application and a compatible Microsoft.AspNetCore.Mvc.Testing package. Some hosting and networking behaviors still require a real network or browser test.
Arrange, act, assert
Arrange only the state needed for the scenario: a known product, an isolated identity and a unique correlation value. Act through the HTTP boundary. Assert the response status and relevant fields, then read persisted state through an independent scope.
Avoid using the exact same in-memory object used by the handler as the sole evidence of persistence. A separate read helps detect missing SaveChanges or transaction mistakes.
The redirect trap
A client may follow a redirect to a login page and return a final 200 response. For a denial-path test, disable automatic redirects or inspect the original response explicitly. Otherwise “success” may mean that HTML for a login page was returned, not that the API accepted the request.
Version note: ASP.NET Core 10 known API endpoints using cookie authentication normally return 401/403 for denied requests. Login redirects remain relevant to older apps, non-API endpoints and custom behavior. Test your actual contract.
Worked review
Weak assertion: response.IsSuccessStatusCode is true. Stronger assertion for the chosen creation contract: status is 201, Location identifies the created resource, the response identifier is nonempty, and a fresh read finds exactly one order with the requested quantity.
Do not assert unstable generated timestamps to the millisecond. Assert the contract's actual precision or inject a controllable clock where time determines behavior.
Exercise
Design a test for a missing required field. State the input, expected status, expected error field and expected database row count. Then change the endpoint to accept the invalid request: your test should fail for a meaningful reason.
Answers to common review questions
- Does an HTTP test prove TLS configuration? Not when traffic stays inside an in-memory test server.
- Does 100% line coverage prove the contract? No; execution is not a correctness assertion.
- Should every business-rule permutation use a full host? Usually keep pure rule combinations in fast unit tests and reserve integration tests for boundaries and wiring.
Check your decision
POST returns 201 with a quantity-4 order priced at 2.50 per item. Which assertion independently checks the persisted result?
Show answer
Correct answer: C
Reading through a fresh scope checks persisted state rather than relying only on the response or a tracked object. The shown price arithmetic is 4 × 2.50 = 10.00.
Hint: Choose evidence that survives the request context.
Watch and apply: free supplementary videos
Benjamin Day's Integration Testing ASP.NET Core with Web Application Factory: Demo 1 introduces xUnit, a factory-created HTTP client, and GET/form POST tests. Open the Video tab or watch on the creator's YouTube channel. This is an MVC/HTML demonstration; strengthen its generic success checks with this lesson's exact API status, media type, fields and persistence checks. Use async Task tests and dispose the factory/client or own them in a correctly scoped fixture. The linked repository currently targets .NET 9 and xUnit 2; its async void example is unsuitable for xUnit v3.
Creator's explanation and code · xUnit guidance on async void
For the database boundary, Milan Jovanović's The Best Way To Use Docker For Integration Testing In .NET is another freely available supplement:
The video is introduced as a PostgreSQL walkthrough; the creator's companion article and sample use SQL Server. The article sample calls MediatR directly, so it does not establish HTTP routing, serialization or authorization coverage. It targets older .NET 7/Testcontainers 3.4 patterns: use compatible current packages, pin database images, initialize the schema and plan per-test data isolation. A shared container alone does not isolate records. See the current official Testcontainers ASP.NET Core example and best practices.
Both videos are optional, original-creator resources available without Full Access. After the introduction, write down the exact response fields and the independent state observation your API test requires. The complete OrdersApi example below is a separate lab; the videos do not demonstrate its assertions.
Response-shape checks that catch quiet regressions
A DTO can ignore an unexpected JSON property. If a field must never be exposed, inspect the actual JSON and assert its absence. For an unordered collection, compare the complete expected items and multiplicity; do not accidentally allow duplicates by comparing sets alone. Preserve ordering checks when order is part of the API contract.
Worked code: turning the contract table into tests
The examples below share a small application, OrdersApi, and a test host, OrdersFactory (covered in the factory lab). Assemble those files with compatible project references before running them. The factory sends HTTP messages through the in-process ASP.NET Core pipeline; it substitutes authentication and outbound pricing, uses SQLite, and normally removes the background publisher. This tests routing, configured authorization, binding, serialization and selected persistence behavior, not real JWT validation, TLS, the pricing service or every exception path.
The application under test
This is a teaching application, not a production security or payment template. Configure real JWT issuer/audience/signature validation separately. Production tenant access needs an explicit validated tenant-membership policy; a null-forgiving operator is not validation. The sample expects one scope claim per permission, whereas some providers put space-separated permissions in one claim. Its sequential idempotency lookup does not define concurrent-conflict or changed-payload behavior. The double money conversion and publisher that merely marks rows are deliberate simplifications: production money should preserve required decimal precision, and delivery needs an actual transport and duplicate-handling design.
// OrdersApi: the small application every test in this course runs against.
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddDbContext<OrdersDb>(o => o.UseSqlite(builder.Configuration.GetConnectionString("Orders") ?? "Data Source=orders.db"));
builder.Services.AddHttpClient<IPricingClient, PricingClient>(c => c.BaseAddress = new Uri(builder.Configuration["Pricing:BaseUrl"] ?? "https://pricing.example.invalid"));
builder.Services.AddHostedService<OutboxPublisher>();
builder.Services.AddAuthentication("Bearer").AddJwtBearer(); // real scheme; tests replace it
builder.Services.AddAuthorization(o => o.AddPolicy("orders:write", p => p.RequireClaim("scope", "orders:write")));
builder.Services.Configure<OrderLimits>(builder.Configuration.GetSection("OrderLimits"));
var app = builder.Build();
app.UseExceptionHandler();
app.UseAuthentication();
app.UseAuthorization();
app.MapPost("/orders", async (CreateOrder req, HttpRequest http, ClaimsPrincipal user, OrdersDb db,
IPricingClient pricing, TimeProvider time, IOptions<OrderLimits> limits, CancellationToken ct) =>
{
var errors = new Dictionary<string, string[]>();
if (req.Quantity < 1) errors["quantity"] = ["Quantity must be at least 1."];
if (req.Quantity > limits.Value.MaxQuantity) errors["quantity"] = [$"Quantity must be at most {limits.Value.MaxQuantity}."];
if (string.IsNullOrWhiteSpace(req.Sku)) errors["sku"] = ["Sku is required."];
if (errors.Count > 0) return Results.ValidationProblem(errors);
var tenant = user.FindFirstValue("tenant")!;
var key = http.Headers["Idempotency-Key"].ToString();
if (key.Length > 0 && await db.Orders.FirstOrDefaultAsync(o => o.TenantId == tenant && o.IdempotencyKey == key, ct) is { } prior)
return Results.Ok(prior);
decimal unitPrice;
try { unitPrice = await pricing.GetPriceAsync(req.Sku, ct); }
catch (HttpRequestException) { return Results.Problem(statusCode: 503, title: "Pricing unavailable"); }
catch (TaskCanceledException) when (!ct.IsCancellationRequested) { return Results.Problem(statusCode: 504, title: "Pricing timed out"); }
var order = new Order { TenantId = tenant, Sku = req.Sku, Quantity = req.Quantity, Total = unitPrice * req.Quantity,
CreatedAt = time.GetUtcNow(), IdempotencyKey = key.Length > 0 ? key : null };
db.Orders.Add(order);
db.Outbox.Add(new OutboxMessage { Type = "OrderCreated", Payload = order.Sku });
await db.SaveChangesAsync(ct);
return Results.Created($"/orders/{order.Id}", order);
}).RequireAuthorization("orders:write");
app.MapGet("/orders/{id:int}", async (int id, ClaimsPrincipal user, OrdersDb db, CancellationToken ct) =>
{
var tenant = user.FindFirstValue("tenant");
var order = await db.Orders.AsNoTracking().FirstOrDefaultAsync(o => o.Id == id && o.TenantId == tenant, ct);
return order is null ? Results.NotFound() : Results.Ok(order); // other tenants get 404, not 403: no existence leak
}).RequireAuthorization();
app.MapGet("/admin/ping", () => "pong").RequireAuthorization(p => p.RequireRole("admin"));
using (var scope = app.Services.CreateScope()) scope.ServiceProvider.GetRequiredService<OrdersDb>().Database.EnsureCreated();
app.Run();
public partial class Program; // optional in ASP.NET Core 10: its source generator already exposes Program
public record CreateOrder(string Sku, int Quantity);
public class OrderLimits { public int MaxQuantity { get; set; } = 100; }
public class Order
{
public int Id { get; set; }
public string TenantId { get; set; } = "";
public string Sku { get; set; } = "";
public int Quantity { get; set; }
public decimal Total { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public string? IdempotencyKey { get; set; }
}
public class OutboxMessage { public int Id { get; set; } public string Type { get; set; } = ""; public string Payload { get; set; } = ""; public bool Published { get; set; } }
public class OrdersDb(DbContextOptions<OrdersDb> o) : DbContext(o)
{
public DbSet<Order> Orders => Set<Order>();
public DbSet<OutboxMessage> Outbox => Set<OutboxMessage>();
protected override void OnModelCreating(ModelBuilder b)
{
b.Entity<Order>().HasIndex(x => new { x.TenantId, x.IdempotencyKey }).IsUnique();
b.Entity<Order>().Property(x => x.Total).HasConversion<double>();
b.Entity<Order>().Property(x => x.CreatedAt).HasConversion(v => v.ToUnixTimeMilliseconds(), v => DateTimeOffset.FromUnixTimeMilliseconds(v));
}
}
public interface IPricingClient { Task<decimal> GetPriceAsync(string sku, CancellationToken ct); }
public class PricingClient(HttpClient http) : IPricingClient
{
public async Task<decimal> GetPriceAsync(string sku, CancellationToken ct)
{
using var r = await http.GetAsync($"/prices/{Uri.EscapeDataString(sku)}", ct);
r.EnsureSuccessStatusCode();
return decimal.Parse(await r.Content.ReadAsStringAsync(ct), System.Globalization.CultureInfo.InvariantCulture);
}
}
public class OutboxPublisher(IServiceScopeFactory scopes, TimeProvider time, ILogger<OutboxPublisher> log) : BackgroundService
{
private readonly TaskCompletionSource _timerReady = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Task TimerReady => _timerReady.Task;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5), time);
_timerReady.TrySetResult();
while (await timer.WaitForNextTickAsync(stoppingToken))
{
using var scope = scopes.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OrdersDb>();
foreach (var m in await db.Outbox.Where(x => !x.Published).ToListAsync(stoppingToken)) m.Published = true;
await db.SaveChangesAsync(stoppingToken);
}
}
}The contract tests
Four behavior-table scenarios are implemented below. Unknown-product behavior, concurrent retries and changed-payload replay still need separate tests. The four tests below check selected parts of two boundaries:
- the HTTP result (status, headers or body, as relevant);
- the side effect (how many rows exist), read through a separate DI scope rather than the request's own
DbContext.
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using OrdersApi.Tests.Infra;
using Xunit;
using Xunit.Abstractions;
namespace OrdersApi.Tests;
// Lesson 1 appendix: the behavior table for POST /orders, executed through the real pipeline.
public class A01_ContractTests(ITestOutputHelper log) : IDisposable
{
private readonly OrdersFactory _f = new();
public void Dispose() => _f.Dispose();
[Fact]
public async Task Valid_request_creates_one_order_readable_through_GET()
{
using var client = _f.ClientFor("t1", "orders:write");
using var res = await client.PostAsJsonAsync("/orders", new { sku = "PEN", quantity = 4 });
Assert.Equal(HttpStatusCode.Created, res.StatusCode);
Assert.Equal("application/json", res.Content.Headers.ContentType?.MediaType);
var created = await res.Content.ReadFromJsonAsync<Order>();
Assert.NotNull(created);
Assert.True(created.Id > 0);
Assert.Equal($"/orders/{created.Id}", res.Headers.Location?.OriginalString);
Assert.Equal("PEN", created.Sku);
Assert.Equal(4, created.Quantity);
Assert.Equal(10.00m, created.Total);
using var getResponse = await client.GetAsync(res.Headers.Location);
Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
var get = await getResponse.Content.ReadFromJsonAsync<Order>();
Assert.NotNull(get);
Assert.Equal(created.Id, get.Id);
Assert.Equal(created.Sku, get.Sku);
Assert.Equal(created.Quantity, get.Quantity);
Assert.Equal(created.Total, get.Total);
var persisted = await _f.WithDb(db => Task.FromResult(db.Orders.Single()));
Assert.Equal(created.Id, persisted.Id);
Assert.Equal("t1", persisted.TenantId);
Assert.Equal("PEN", persisted.Sku);
Assert.Equal(4, persisted.Quantity);
Assert.Equal(10.00m, persisted.Total);
log.WriteLine($"POST -> {(int)res.StatusCode}, Location={res.Headers.Location}; independent order verified");
}
[Fact]
public async Task Invalid_quantity_is_a_validation_problem_and_persists_nothing()
{
var res = await _f.ClientFor("t1", "orders:write").PostAsJsonAsync("/orders", new { sku = "PEN", quantity = 0 });
int rows = await _f.WithDb(db => Task.FromResult(db.Orders.Count()));
log.WriteLine($"quantity 0 -> {(int)res.StatusCode} {res.Content.Headers.ContentType?.MediaType}; rows in DB={rows}");
Assert.Equal(HttpStatusCode.BadRequest, res.StatusCode);
Assert.Equal("application/problem+json", res.Content.Headers.ContentType?.MediaType);
using var body = JsonDocument.Parse(await res.Content.ReadAsStringAsync());
Assert.Equal(400, body.RootElement.GetProperty("status").GetInt32());
Assert.True(body.RootElement.GetProperty("errors").GetProperty("quantity").GetArrayLength() > 0);
Assert.Equal(0, rows);
Assert.Equal(0, await _f.WithDb(db => Task.FromResult(db.Outbox.Count())));
}
[Fact]
public async Task Anonymous_caller_is_denied_without_a_redirect_and_persists_nothing()
{
var res = await _f.ClientFor(null).PostAsJsonAsync("/orders", new { sku = "PEN", quantity = 1 });
int rows = await _f.WithDb(db => Task.FromResult(db.Orders.Count()));
log.WriteLine($"anonymous -> {(int)res.StatusCode}, Location header present: {res.Headers.Location is not null}; rows in DB={rows}");
Assert.Equal(HttpStatusCode.Unauthorized, res.StatusCode);
Assert.Null(res.Headers.Location);
Assert.Equal(0, rows);
}
[Fact]
public async Task Duplicate_idempotency_key_replays_the_first_order()
{
var client = _f.ClientFor("t1", "orders:write");
client.DefaultRequestHeaders.Add("Idempotency-Key", "k-1");
using var first = await client.PostAsJsonAsync("/orders", new { sku = "PEN", quantity = 1 });
Assert.Equal(HttpStatusCode.Created, first.StatusCode);
var a = await first.Content.ReadFromJsonAsync<Order>();
Assert.NotNull(a);
var second = await client.PostAsJsonAsync("/orders", new { sku = "PEN", quantity = 1 });
Assert.Equal(HttpStatusCode.OK, second.StatusCode);
var b = await second.Content.ReadFromJsonAsync<Order>();
Assert.NotNull(b);
int rows = await _f.WithDb(db => Task.FromResult(db.Orders.Count()));
log.WriteLine($"same key twice -> ids {a!.Id} and {b!.Id}, second status {(int)second.StatusCode}; rows in DB={rows}");
Assert.Equal(a.Id, b.Id);
Assert.Equal(1, rows);
}
}Expected observations
With the factory returning a unit price of 2.50 and a fresh database per test:
- Valid creation: 201, a resource Location, matching POST/GET fields, and one independently read order with quantity 4 and total 10.00.
- Invalid quantity: 400, a quantity validation error, zero orders and zero outbox records.
- Anonymous request: 401, no redirect Location and no order.
- Sequential replay: first response 201, second response 200, the same identifier and one order.
Run the assembled tests and inspect any failure at its first assertion.
Why each test can catch a real regression
- Happy path.
- It asserts 201, the
Locationheader, and thatGETon that location returns the same total. - Breaking the asserted route, fields or price arithmetic (4 × 2.50) fails it. Typed deserialization still does not prove an exact JSON schema or absence of extra fields; use the raw-JSON checks described above when those are contract requirements.
- It asserts 201, the
- Validation.
- It asserts 400 with
application/problem+json, a nonempty quantity error and zero order/outbox rows. - A refactor that saves before validating passes a status-only check but fails here.
- It asserts 400 with
- Anonymous caller.
- It asserts 401 and no
Locationheader. - ASP.NET Core 10 known API endpoints normally keep 401/403 even with cookie authentication. If custom behavior reintroduces a login redirect,
AllowAutoRedirect = falseexposes its 302 so this status assertion fails.
- It asserts 401 and no
- Idempotency.
- The same
Idempotency-Keytwice returns the same id, and only one row exists. - Deleting the lookup fails this sequential replay check. Detecting a missing tenant predicate requires another tenant to reuse the same key; this one-tenant test cannot establish that isolation.
- The same
Assemble the runnable lab
Prerequisites: C# async/await, Minimal API routing, dependency injection, EF Core and basic xUnit assertions. The app and tests target .NET 10. The written design exercises for provider SQL, real tokens, shipment replay and crash recovery need additional implementations; the sample does not silently supply those guarantees.
Create sibling folders OrdersApi and OrdersApi.Tests under one solution directory. Save these project files, then copy each complete listing into its named file. Do not paste every snippet into one file; the short excerpts explain or extend a listing. Remove any template-generated test file if you started from a template.
OrdersApi/OrdersApi.csproj
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net10.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.12"/> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.12"/> </ItemGroup> </Project>
OrdersApi.Tests/OrdersApi.Tests.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net10.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> <IsTestProject>true</IsTestProject> </PropertyGroup> <ItemGroup> <ProjectReference Include="../OrdersApi/OrdersApi.csproj"/> <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.12"/> <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.12"/> <PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.1.0"/> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1"/> <PackageReference Include="xunit" Version="2.9.3"/> <PackageReference Include="xunit.runner.visualstudio" Version="2.8.2"/> </ItemGroup> </Project>
This compatible setup uses ASP.NET Core/EF Core 10.0.12, TimeProvider.Testing 10.1.0, xUnit v2 2.9.3 and its 2.8.2 Visual Studio runner. Keep compatible package patches current; major versions and xUnit v3 are not interchangeable setup substitutions. The explicit public Program declaration in the app remains valid; normal ASP.NET Core 10 already supplies the necessary public visibility. ASP0027
| Complete file | Copy from |
|---|---|
| OrdersApi/Program.cs | The application under test in this lesson |
| OrdersApi.Tests/A01_ContractTests.cs | The contract tests in this lesson |
| OrdersApi.Tests/OrdersFactory.cs and L05_FactoryTests.cs | Factory customization |
| OrdersApi.Tests/L06_DatabaseTests.cs | Database realism code lab |
| OrdersApi.Tests/L07_AuthTests.cs | Authentication and authorization code lab |
| OrdersApi.Tests/L08_OutboundHttpTests.cs | Outbound HTTP code lab |
| OrdersApi.Tests/L09_TimeAndBackgroundTests.cs | Time and background work |
| OrdersApi.Tests/L10_SharedHostTests.cs and OrdersHostCollection.cs | Shared fixtures |
| OrdersApi.Tests/L11_ErrorContractTests.cs | Error contracts |
Run these commands from the parent directory after saving the files. Keeping the solution above the app also lets WebApplicationFactory locate its content root.
dotnet new sln -n Orders --format sln dotnet sln Orders.sln add OrdersApi/OrdersApi.csproj OrdersApi.Tests/OrdersApi.Tests.csproj dotnet test OrdersApi.Tests/OrdersApi.Tests.csproj --logger "console;verbosity=detailed"
Start with Program, OrdersFactory and A01_ContractTests for four HTTP-contract cases, then add the named labs. With all listed test classes the suite contains 35 cases, including theory rows. Inspect the first failed assertion and its branch; a count of green tests does not expand the boundaries they exercise.
The lab uses in-process TestServer, private SQLite databases, fake authentication, a primary-handler pricing stub and controlled application time. It does not contact the real pricing service or prove deployed network behavior, real JWT validation, production-engine SQL, migrations, durable delivery or concurrent idempotency.
Quick reference
- Send the public HTTP method and path through the configured application pipeline.
- Assert exact status, relevant headers, response shape, and meaningful values.
- Disable automatic redirects when testing the original redirect response.
- Arrange explicit, isolated state; a new HttpClient does not reset a database.
- Verify writes through a fresh scope and DbContext after the request completes.
- Test rejected input and missing resources, including required absence of side effects.
- Replace dependencies inside the test host and verify the replacement was actually used.
Practice
TechInterviewNotes Editorial Team · Updated 28 Oct 2026 ·