ASP.NET Core Integration Testing
Test the real ASP.NET Core pipeline with WebApplicationFactory, controlled dependencies, realistic databases, authenticated clients, and stable assertions on public contracts.
Host the application in integration tests
Control database and external dependencies
Assert HTTP contracts and security behavior
The short answer
Integration tests should exercise routing, binding, middleware, authorization, serialization, and persistence together through HTTP. Replace only external boundaries deliberately, isolate test data, and assert status, headers, and response contracts.
Build the runtime mental model
WebApplicationFactory boots the application with a test host and produces HttpClient instances that traverse the ASP.NET Core pipeline. This catches composition failures that isolated handler tests cannot see.
Advanced C# work improves when you separate language syntax, runtime behavior, and application policy. Write down which layer owns the guarantee in this lesson. Then identify the observable evidence—a compiler rejection, test result, generated query, trace, or measurement—that would prove the model correct.
Design the boundary deliberately
Override registrations for a disposable database, fake clock, or stub outbound HTTP handler. Seed data per test, use unique identifiers, and reset state deterministically. Authentication test schemes can produce controlled claims without weakening production configuration.
The starter isolates one part of the mental model so it can run in the browser. The exercise moves the same rule into a current local .NET project where packages, framework hosting, diagnostics, and multi-file tests are available.
using System;
class Response
{
public int Status { get; private set; }
public Response(int status) { Status = status; }
}
class Program
{
static void AssertStatus(int expected, Response actual)
{
if (actual.Status != expected) throw new Exception("Unexpected status.");
}
static void Main() { AssertStatus(201, new Response(201)); Console.WriteLine("passed"); }
}Expected output
passed
Diagnose failure and misuse
Mocking the endpoint handler bypasses the feature being tested. A shared mutable database creates order-dependent failures. In-memory providers may differ materially from the production database. Snapshotting volatile timestamps makes tests brittle.
Classify each failure as a contract violation, transient operational failure, permanent dependency response, concurrency conflict, or programmer defect. That classification determines whether to reject, retry, compensate, cancel, or fail fast. A generic catch-and-continue policy destroys the information needed to make that decision.
| Question | Evidence to inspect | Decision |
|---|---|---|
| Is the input valid? | Validation result and boundary examples | Reject with a stable contract |
| Is the failure transient? | Typed status, exception, and policy context | Retry only when bounded and safe |
| Is state still consistent? | Invariant and transaction outcome | Commit, compensate, or abort |
| Is performance acceptable? | Representative latency and allocation data | Keep simple or optimize one cause |
Apply the concept in production
Run focused unit tests quickly and a smaller integration suite at build gates. Include unauthorized, forbidden, malformed, conflict, not-found, successful, and persistence-reload paths. Keep failure output useful enough to reproduce locally.
Finish by making the result operable. Add structured diagnostics at the boundary, propagate cancellation, avoid sensitive data, and record SDK and dependency versions. Test the public behavior instead of private implementation details. If a framework or provider performs translation, serialization, concurrency, or I/O, include at least one test against the real production technology.
A senior-level review should be able to answer four questions: what contract is promised, who owns lifetime and cleanup, how failures become visible, and what evidence supports the design. If any answer depends on “the framework probably handles it,” inspect the documentation or runtime behavior and turn the assumption into a checked decision.
Quick knowledge check
Answer before you reveal.
01What does an HTTP integration test cover that a handler unit test does not?
It exercises routing, middleware, model binding, authorization, serialization, dependency composition, and the selected persistence boundary together.
02What must happen before adding complexity to this design?
State the requirement, preserve a correct baseline, collect evidence, and explain how the proposed mechanism improves a specific quality.
Exercise
Practice challenge
Create a WebApplicationFactory suite for order creation and retrieval, including validation, authorization, database isolation, and contract assertions.
Requirements
- The implementation states its contract and ownership boundary explicitly
- Automated checks cover the successful path and at least two meaningful failures
- Diagnostics expose failure context without secrets or swallowed exceptions
- The project documents required SDK, packages, setup, run, and test commands
Optional extension: Measure or load-test the critical path and record whether the evidence justifies another optimization or abstraction.
Open in C# compilerLesson checkpoint
One small step locks it in
Mark this lesson complete, then keep the momentum going.
Clear up the details
Frequently asked questions
When should I use asp.net core integration testing?
Use it when its explicit tradeoff solves a measured requirement or clarifies an owned boundary. Keep the simpler design when the additional mechanism does not improve correctness, operability, or changeability.
Does the browser compiler cover the complete production setup?
No. It runs the focused starter program. Framework, package, database, benchmark, and multi-project work requires a current local .NET SDK and the project commands described in the exercise.
What evidence should I keep after the exercise?
Keep the acceptance cases, automated tests, diagnostic or benchmark output where relevant, and a short decision note describing the chosen boundary and rejected alternative.