Unit, Integration, and Contract Testing for APIs
Build an API test strategy with fast unit tests, realistic integration checks, and consumer contract tests without relying on brittle end-to-end suites.
API teams can build a test strategy around the boundary each check needs to protect: business rules, real framework and database behavior, consumer contracts, or a critical end-to-end flow. The guide shows how to test observable responses, verify versioned contracts in CI, handle flaky tests, and protect test data. These distinctions help teams catch failures early without letting a slow, brittle suite dominate feedback.
Unit, Integration, and Contract Testing for APIs
Introduction
An API change can fail in several places. A validation rule may be wrong, the database may handle a duplicate request differently than a mock, or a provider may return a response that one of its consumers cannot use.
Those failures need different checks. This guide follows one POST /payments behavior through unit, integration, and consumer/provider contract tests. Each test crosses a different boundary and answers a specific question.
One payment flow, three test layers
Assume the API accepts a payment with a positive amount. A client may retry the same request with the same Idempotency-Key; the retry should return the original payment instead of creating another one. The response contains an ID and a status.
The layers below use that behavior as a running example. The exact test framework and payment model will vary, but the boundaries should not.
1. Unit test the rule
A unit test exercises the local decision without starting the web server or database. For example, payment validation can reject a zero or negative amount:
it("rejects a non-positive payment amount", () => {
expect(validatePayment({ amount: 0, currency: "USD" })).toEqual({
ok: false,
code: "INVALID_AMOUNT",
});
});
This test should be fast and deterministic. A fake clock or repository can help when the rule depends on time or stored state, but the fake should not pretend to prove SQL constraints or transaction behavior.
2. Integrate at a real boundary
An integration test sends an HTTP request through the API’s route and middleware and uses the same database engine and migrations the service relies on. It can catch mistakes a unit test cannot, such as incorrect serialization, a missing constraint, or an idempotency race.
it("returns the saved payment when a request is replayed", async () => {
const firstResponse = await testApp.request("/payments", {
method: "POST",
headers: { "Idempotency-Key": "order-812" },
body: JSON.stringify({ amount: 1250, currency: "USD" }),
});
const replayResponse = await testApp.request("/payments", {
method: "POST",
headers: { "Idempotency-Key": "order-812" },
body: JSON.stringify({ amount: 1250, currency: "USD" }),
});
const first = await firstResponse.json();
const replay = await replayResponse.json();
expect(firstResponse.status).toBe(201);
expect(replayResponse.status).toBe(201);
expect(replay.id).toBe(first.id);
expect(await db.paymentCount()).toBe(1);
});
Here testApp is wired to the application’s real router and a disposable database. The test must apply production migrations and clean up its data. An in-process HTTP client is enough when the socket itself is not under test; use a real network boundary when proxying, TLS, or server configuration could change the result.
3. Verify the consumer/provider contract
A consumer contract records what a client sends and the response it needs. For this flow, the contract includes the Idempotency-Key request header and a successful response with a string id and status: "accepted". The consumer test checks those expectations against the client code. The provider build then runs the published, versioned contract against its candidate API.
Keep the assertion on the serialized exchange. Matching a response shape in a shared TypeScript type does not prove that the provider sends that shape over HTTP.
{
"request": {
"method": "POST",
"path": "/payments",
"headers": { "Idempotency-Key": "order-812" }
},
"response": {
"status": 201,
"body": {
"id": "a string",
"status": "accepted"
}
}
}
Contract tools use their own matcher syntax; the example shows the expectation, not a drop-in Pact file. The consumer publishes a versioned contract after its test passes. The provider verifies its candidate against active contracts and attaches the result to that build. A deployment check can then require a passing result for the consumers served by that version.
Contracts cover declared consumer expectations. They do not replace provider tests for internal invariants or behaviors no consumer has specified. Remove an old contract only after its consumer no longer depends on it.
Keep full-flow tests focused
An end-to-end test can prove that the deployed client and API work together, but it is a poor place to check every validation branch. A small number of critical user journeys can be useful; a large suite of duplicated scenarios tends to run slowly and makes failures harder to locate.
For broader suite scheduling, parallel execution, flaky-test handling, and release gates, see Automated Testing in CI/CD: Strategies and Quality Gates. This article stays focused on the API boundaries those suites need to cover.
Failure cases worth keeping visible
- A mock accepts a dependency call, but the real service returns
429. Cover the relevant error response and retry policy at an integration boundary. - An in-memory database accepts data that production rejects. Run migrations and constraints against the production database engine.
- A contract passes because consumer and provider share generated types, but their HTTP serialization differs. Verify the wire format.
- A flaky test passes only after reruns. Control shared state, clocks, randomness, and external calls. If a test must be quarantined, give it an owner and an expiry date.
Protect test data, access, and reports
Use synthetic identities and records by default. If a regulation or incident investigation requires production-derived data, document approval, de-identification, access limits, and a deletion date. Give CI identities only the roles needed for their checks, and include allowed, denied, and cross-tenant cases in authorization coverage.
Treat test reports, snapshots, and contract artifacts as data. Redact secrets and personal fields, restrict access, and set retention to match their diagnostic value. For audit-relevant checks, record the API version and contract artifact with the build, never credentials. Do not print full tokens or request payloads when a test fails.
Compare the test boundaries
| Test approach | What it can establish | Cost or limit | Good fit |
|---|---|---|---|
| Unit test with fakes | Validation, mapping, and branching rules | Cannot prove framework wiring or database behavior | Many edge cases in local business logic |
| Integration test with real dependencies | Routing, middleware, migrations, transactions, and serialization | Slower setup; containers and cleanup need ownership | Boundaries where framework or database behavior matters |
| Consumer/provider contract | Compatibility with recorded consumer expectations | Teams must publish and verify versioned contracts | Independently deployed services with known consumers |
| End-to-end test | A critical workflow across deployed components | Slow, and failures can be hard to localize | A small number of user journeys that cross boundaries |
Common pitfalls
- Checking only status codes: assert response shape, authorization, side effects, and error semantics too.
- Sharing production implementation with test helpers: a fake that calls the same serializer may repeat the same defect. Exercise the wire format at the integration boundary.
- Treating contracts as exhaustive: keep provider tests for behavior the contract does not describe.
- Normalizing flaky tests: reruns can hide nondeterminism. Track an owner and removal date for any quarantine.
Observability checklist
- Report duration, failure category, and the boundary each test covers.
- Track flaky tests and rerun rates instead of hiding retries.
- Attach contract verification results to the build artifact.
- Record which API routes and error cases lack coverage.
- After deployment, run a small smoke check and watch real error rates.
Quick recap
- Use unit tests for local rules.
- Use real dependencies when framework, database, or protocol behavior matters.
- Verify consumer-visible requests, responses, and errors against the provider.
- Keep end-to-end coverage small enough that failures remain useful.
- Protect test credentials, data, and artifacts.
Interview questions
It checks that a provider's observable API behavior matches assumptions a consumer has recorded, such as request fields, response schema, and selected error cases.
Mocks are fast, but they can repeat a team's assumptions instead of the dependency's behavior. Integration tests catch differences in serialization, database semantics, middleware, and protocol handling.
Find the nondeterminism, such as shared state, uncontrolled time, or external network calls. A temporary quarantine needs an owner and removal date so failures do not become invisible.
An integration test should use the real database engine and migrations, because a mock or in-memory substitute may not enforce the same constraints.
Existing consumers can keep getting the behavior they depend on. Adding an optional response field is often compatible, while removing a field or changing its meaning can break them.
Verify the provider candidate against active, versioned consumer contracts and attach the result to that exact build. Deployment can then require successful verification for the consumers served by that version.
Contracts cover declared consumer expectations, not every provider behavior or edge case. Provider tests still need to cover internal invariants and behaviors consumers have not specified.
Further reading
- API contracts explains how to define and evolve consumer-visible guarantees.
- OpenAPI and machine-readable specifications covers describing API shapes in a form that tools can validate.
- API examples, schemas, and error documentation shows how schemas and examples help consumers understand the wire contract.
- Pact documentation explains consumer-driven contracts and provider verification.
- The Practical Test Pyramid discusses balancing test scope, feedback speed, and maintenance cost.
Conclusion
Tests help when their scope matches the failure you want to catch. Check local rules in isolation, exercise real boundaries with real dependencies, and verify consumer expectations against the provider’s wire behavior. Keep full-flow checks focused, and make failures clear enough that the team can act on them.
Category
Related Posts
Consumer-Driven Contract Testing for Backend Services
Learn how consumers define API expectations and providers verify them in CI, with practical workflows, failure modes, and deployment safeguards.
GraphQL Federation: Subgraphs, Routing, and Trade-offs
Learn how GraphQL federation composes subgraphs, routes operations, and affects service ownership, query planning, latency, failure handling, and authorization.
API Clients, Servers, and Network Boundaries Explained
Understand what API clients and servers each own, how network boundaries fail, and how timeouts, retries, and trust boundaries shape reliable integrations.