Web integration tests
Web integration tests
A web integration test sends a request through a real application pipeline and checks the observable contract, not just a controller method. TestServer runs that pipeline in-process without a public listener.
Use a unit test for business calculations and a web integration test for routing, middleware, binding, dependency injection, authorization and response formatting. TestServer builds a host with an in-memory HTTP transport. WebApplicationFactory<TEntryPoint> additionally boots an existing application entry point and manages host/client lifecycle; use a separate test project, a public entry-point type (for top-level Program, a public partial Program declaration is common), ConfigureWebHost/ConfigureTestServices to replace only the required services, and CreateClient with redirects disabled when checking challenges. For a real application, explicitly replace or reject production connection configuration before startup; never let a test silently use live credentials. A test authentication handler proves policy behavior with controlled identities, not JWT signature verification, cookies, TLS or a real identity provider. Add distinct approved loopback Kestrel tests for socket behavior and browser tests for interaction. Check status, media type, meaningful body fields and headers rather than relying on status alone. Each executable below is a standalone assertion harness (throws on failure), not an xUnit-discovered test suite. The optional WAF workflow is described in the companion test plan. A complete separate two-project WebApplicationFactory harness is at lab-fixtures/testing/waf-stock; its test entry point uses a synthetic application with no external dependencies.
Baseline: .NET 10 / C# 14. All C# results below are reasoned, not executed. Models, in-process integrations and actual runtime or UI tests are distinguished.
Assert the HTTP status and JSON contract
A known SKU returns a JSON object; an unknown SKU returns 404. The client timeout bounds requests.
Inspect the archived Fixture.csproj and use only an approved .NET 10 SDK. Build and run in an isolated lab with finite time and resource limits. Requires the ASP.NET Core 10 shared framework. Requires reviewed Microsoft.AspNetCore.TestHost 10.0.15 dependencies. No real listener or network service is needed.
using System;using System.Net;using System.Net.Http;using System.Net.Http.Json;using System.Text.Json;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.TestHost;using Microsoft.Extensions.Logging;var builder = WebApplication.CreateBuilder();builder.Logging.ClearProviders();builder.WebHost.UseTestServer();await using var app = builder.Build();app.MapGet("/stock/{sku}", (string sku) => sku == "A" ? Results.Ok(new { sku, available = 3 }) : Results.NotFound());await app.StartAsync();using var client = app.GetTestClient();client.Timeout = TimeSpan.FromSeconds(5);using var ok = await client.GetAsync("/stock/A");using var body = JsonDocument.Parse(await ok.Content.ReadAsStringAsync());if (ok.StatusCode != HttpStatusCode.OK || ok.Content.Headers.ContentType?.MediaType != "application/json" || body.RootElement.GetProperty("sku").GetString() != "A" || body.RootElement.GetProperty("available").GetInt32() != 3) throw new Exception("stock contract failed");using var missing = await client.GetAsync("/stock/B");if (missing.StatusCode != HttpStatusCode.NotFound) throw new Exception("missing contract failed");Console.WriteLine("stock contract passed; missing=404");await app.StopAsync();Expected result (not executed):
stock contract passed; missing=404This is a real routed HTTP contract through TestServer, but no TCP listener is involved. JsonDocument verifies the actual serialized response fields.
Distinguish anonymous, wrong role and wrong tenant
A test-only authentication scheme issues claims for three fixed synthetic identities. Never register this scheme in a deployed application.
Inspect the archived Fixture.csproj and use only an approved .NET 10 SDK. Build and run in an isolated lab with finite time and resource limits. Requires the ASP.NET Core 10 shared framework. Requires reviewed Microsoft.AspNetCore.TestHost 10.0.15 dependencies. No real listener or network service is needed.
using System;using System.Net;using System.Net.Http;using System.Net.Http.Json;using System.Text.Json;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.TestHost;using System.Security.Claims;using System.Text.Encodings.Web;using System.Threading.Tasks;using Microsoft.AspNetCore.Authentication;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using Microsoft.Extensions.Options;var builder = WebApplication.CreateBuilder();builder.Logging.ClearProviders();builder.WebHost.UseTestServer();builder.Services.AddAuthentication("LabOnly").AddScheme<AuthenticationSchemeOptions, LabAuth>("LabOnly", _ => { });builder.Services.AddAuthorization();await using var app = builder.Build();app.UseAuthentication(); app.UseAuthorization();app.MapGet("/tenants/{tenant}/stock", (string tenant, ClaimsPrincipal user) => user.FindFirst("tenant")?.Value == tenant ? Results.Ok(new { available = 3 }) : Results.Forbid()) .RequireAuthorization(policy => policy.RequireRole("reader"));await app.StartAsync();using var client = app.GetTestClient(); client.Timeout = TimeSpan.FromSeconds(5);foreach (var (identity, expected) in new[] { ("none", 401), ("viewer", 403), ("other", 403), ("reader", 200) }) { using var req = new HttpRequestMessage(HttpMethod.Get, "/tenants/A/stock"); if (identity != "none") req.Headers.Add("X-Lab-Identity", identity); using var res = await client.SendAsync(req); if ((int)res.StatusCode != expected) throw new Exception("authorization mismatch"); if (expected == 200) { using var doc = JsonDocument.Parse(await res.Content.ReadAsStringAsync()); if (doc.RootElement.GetProperty("available").GetInt32() != 3) throw new Exception("body mismatch"); } Console.WriteLine($"{identity}: {expected}");}await app.StopAsync();sealed class LabAuth(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder) { protected override Task<AuthenticateResult> HandleAuthenticateAsync() { string name = Request.Headers["X-Lab-Identity"].ToString(); if (name is not ("viewer" or "other" or "reader")) return Task.FromResult(AuthenticateResult.NoResult()); var claims = new[] { new Claim(ClaimTypes.Name, name), new Claim(ClaimTypes.Role, name == "viewer" ? "viewer" : "reader"), new Claim("tenant", name == "other" ? "B" : "A") }; return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme.Name)), Scheme.Name))); }}Expected result (not executed):
none: 401viewer: 403other: 403reader: 200A challenge differs from a forbidden authenticated request. Resource ownership must be checked in addition to the role. This handler is confined to the synthetic in-process host; arbitrary headers are not production authentication.
Verify safe validation error details
Send an invalid quantity. Assert the machine-readable error and ensure an internal diagnostic is not returned.
Inspect the archived Fixture.csproj and use only an approved .NET 10 SDK. Build and run in an isolated lab with finite time and resource limits. Requires the ASP.NET Core 10 shared framework. Requires reviewed Microsoft.AspNetCore.TestHost 10.0.15 dependencies. No real listener or network service is needed.
using System;using System.Net;using System.Net.Http;using System.Net.Http.Json;using System.Text.Json;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.TestHost;using Microsoft.Extensions.Logging;var builder = WebApplication.CreateBuilder();builder.Logging.ClearProviders(); builder.WebHost.UseTestServer();await using var app = builder.Build();app.MapPost("/reserve", (Reservation input) => input.Units <= 0 ? Results.ValidationProblem(new System.Collections.Generic.Dictionary<string, string[]> { ["units"] = new[] { "Must be positive" } }) : Results.Ok(new { accepted = true }));await app.StartAsync();using var client = app.GetTestClient(); client.Timeout = TimeSpan.FromSeconds(5);using var invalid = await client.PostAsJsonAsync("/reserve", new Reservation(0));string text = await invalid.Content.ReadAsStringAsync();using var doc = JsonDocument.Parse(text);if ((int)invalid.StatusCode != 400 || invalid.Content.Headers.ContentType?.MediaType != "application/problem+json" || doc.RootElement.GetProperty("errors").GetProperty("units")[0].GetString() != "Must be positive" || text.Contains("StackTrace", StringComparison.OrdinalIgnoreCase)) throw new Exception("validation contract");using var valid = await client.PostAsJsonAsync("/reserve", new Reservation(2));if (!valid.IsSuccessStatusCode) throw new Exception("valid request failed");Console.WriteLine("invalid=400; valid=200; error field checked");await app.StopAsync();sealed record Reservation(int Units);Expected result (not executed):
invalid=400; valid=200; error field checkedThe assertion covers this explicit validation branch only, not global exception redaction or all malformed input. In the approved full suite also assert exact valid status, body, malformed JSON, cancellation and exception handling.
Apply the concept
Extend the authorization matrix with a reader from tenant A requesting tenant B and an unknown identity requesting A. Explain which test type is needed to validate a signed JWT and real TLS.
Use the manual practice and knowledge check. Do not deploy or publish these fixtures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Web integration tests — knowledge check
Apply the lesson concepts to the following scenarios.
What does TestServer exercise?
Why disable auto-redirect when checking a cookie challenge?
What does a 403 for the wrong tenant establish here?
What is a strong JSON assertion?
How should test database configuration be handled?