Software Testing
Microservices Testing Strategies
This course teaches the testing practices a team needs once an application is split into independently deployable services. It covers why a monolith's testing habits break down at the service boundary, how to balance unit tests, contract tests, integration tests and end-to-end checks across a distributed system, how to keep a test suite fast and reliable when services call each other over a network, and how to use test doubles, service virtualization concepts and contract testing to verify a service without starting every one of its dependencies. The course also looks at data consistency across services, versioning a public API without breaking consumers, and the role of observability once tests alone cannot cover every path a request can take through a system. By the end, a learner can design a testing strategy for a microservices architecture that catches integration problems early without turning every test run into a slow, flaky exercise in starting a dozen containers.
Intermediate · By the Xtest team · About 55 minutes to read
Introduction
A microservices architecture trades one large, predictable deployable for many small, independently deployable services that talk to each other over a network. That trade brings real benefits for a team's ability to ship independently, but it changes what testing has to answer for. A single request a user makes might now pass through five or six services, each owned by a different team, each with its own release schedule, each capable of being down, slow or returning a shape of data nobody expected. A test suite built the way a monolith's was built, mostly unit tests with a handful of end-to-end tests run against one deployed copy of everything, tends to either miss the problems that only show up between services, or answer them by standing up the whole system for every test run, which is slow and brittle. This course works through a more deliberate approach: a mix of fast unit tests inside each service, contract tests that check two services agree on the shape of a request and response without either one having to run the other, integration tests that exercise a service against its real dependencies in a controlled environment, and a thin layer of end-to-end tests that confirm a complete user journey still works across the whole system. Along the way the course covers test doubles, consumer-driven contracts, data consistency across service boundaries, and how to keep a growing test suite fast enough that a team still runs it on every change. The goal is a strategy that catches a breaking change in one service before it reaches another team's service in production.
Understanding the Microservices Testing Challenge
A monolith fails or succeeds as one process. A microservices architecture is a network of processes, and the first thing a testing strategy has to accept is that the network itself is now part of what gets tested. A call from one service to another can be slow, can time out, can return a 500, or can simply disappear, and a test suite that never exercises those paths will pass right up until the day one of them happens in production.
The second thing to accept is that services are usually owned, versioned and deployed independently. Service A's team can ship a change on Tuesday that Service B's team never sees until it breaks their production traffic on Wednesday. A testing strategy that only tests each service in isolation, and only tests the whole system in one slow nightly run, leaves a wide gap in the middle, exactly where most real incidents in a distributed system start: at the boundary between two services, in the shape of a request or response neither side fully controls.
The third thing is data. In a monolith one database transaction either commits or rolls back. Across services, data for one logical operation can live in several databases, updated by several services, and there is no single transaction tying them together. A test suite has to be able to check that data stays consistent across that journey, not just that each service's own database looks right in isolation.
This section lays the groundwork: why a flat pyramid of "lots of unit tests, one big end-to-end suite" does not fit a distributed system, and what a test pyramid shaped for microservices looks like instead. The sections that follow build out each layer of that pyramid: contract tests between services, integration tests against real dependencies, and a thin top layer of full-journey tests.
Why Traditional Testing Approaches Fall Short
A traditional test pyramid, built for a single deployable, assumes that once a unit test passes, the only thing left to check is the behavior of one codebase end to end. That assumption breaks the moment a request has to cross a network boundary. A unit test for Service A can mock its call to Service B with whatever response the author of the test imagines, and that mock can quietly drift out of step with what Service B actually returns after its next deploy. The test keeps passing. The two services, running together, do not.
End-to-end tests seem like the obvious fix, since they run the whole system together and would catch that drift. In practice they come with a cost that scales badly: standing up every service and its dependencies for a test run is slow, and a flaky network call or a service that takes an extra second to start turns a reliable test into an unreliable one. Teams that lean entirely on end-to-end tests for microservices usually end up with a suite that takes a long time to run, fails for reasons that have nothing to do with the code under test, and gets skipped or ignored under deadline pressure, which defeats the purpose of having it.
The practical answer is not to drop either layer, but to add a layer in between that a monolith never needed: a way to check that two services agree on the shape of what they exchange, without needing both services running together. That is what contract testing is for, and it is covered later in this course. The point to take from this subsection is that a distributed system needs a distributed answer to each layer of the pyramid, not just a bigger end-to-end suite at the top.
The Microservices Test Pyramid
A test pyramid built for microservices keeps the same shape as a traditional one, many fast tests at the bottom and few slow ones at the top, but each layer answers a different question. At the bottom, unit tests check a single service's own logic in isolation, with no network calls at all: given this input, does this function return the right output. These are the fastest tests in the suite and should make up the bulk of it.
Above that sits contract testing, a layer a monolith never needs. A contract test checks that a service which calls another service (the consumer) and the service being called (the provider) agree on the shape of the request and response between them, without either one running the other for real. This catches a breaking change in an API's shape before it ever reaches a shared environment.
Above that sits integration testing: a service is tested against its real dependencies, whether that is a real database, a message queue, or another service, usually running in containers for the duration of the test run. This layer answers a different question than a contract test: not just "do we agree on the shape of the data" but "does this service actually behave correctly when it talks to the real thing."
At the top sits a thin layer of end-to-end tests that follow one complete user journey through several services, confirming the system works together as a whole. Because this layer is slow and more prone to flakiness, it should cover only the handful of journeys that matter most, not every possible path through the system. Getting the balance right across these four layers is the core skill this course builds toward.
// order-service.test.js
// A fast unit test: no network call, no database, just the service's own logic
const { calculateOrderTotal } = require('./order-service');
test('applies a 10% discount when quantity is 10 or more', () => {
const items = [{ price: 20, quantity: 10 }];
const total = calculateOrderTotal(items);
expect(total).toBe(180); // 200 - 10%
});
test('charges full price when quantity is below 10', () => {
const items = [{ price: 20, quantity: 3 }];
const total = calculateOrderTotal(items);
expect(total).toBe(60);
});
A unit test for a single service's pricing logic, written with Jest. It has no network call and no dependency on any other service, so it runs in milliseconds and belongs at the base of the test pyramid.
# A simple integration smoke check run after docker-compose brings services up
# Confirms the order service can actually reach the inventory service over the network
docker-compose up -d
until curl -sf http://localhost:8081/health > /dev/null; do
echo "waiting for inventory-service..."
sleep 2
done
RESPONSE=$(curl -s -X POST http://localhost:8080/orders \
-H 'Content-Type: application/json' \
-d '{"itemId": "sku-123", "quantity": 2}')
echo "$RESPONSE" | jq -e '.status == "confirmed"' \
&& echo "PASS: order confirmed against real inventory-service" \
|| (echo "FAIL: order was not confirmed" && exit 1)
An integration check, using curl and jq, that starts real containers with docker-compose and confirms one service can place an order that another service, running for real, actually confirms. This belongs higher up the pyramid than a unit test, since it exercises a real network call.
Tips
- Keep unit tests free of any network call or container dependency; if a test needs docker-compose to run, it belongs in the integration layer, not the unit layer.
- Name each test by the layer it belongs to (unit, contract, integration, end-to-end) in its file path or test tag, so the team can run just the fast layers on every commit and save the slow layers for a later stage of the pipeline.
- When an end-to-end test fails, check first whether the failure is really in the code under test or in the network and environment around it; a flaky end-to-end suite that nobody trusts is worse than no end-to-end suite at all.
Common pitfalls
- Mocking a downstream service's response by hand in a unit test and never updating the mock when the real service changes its response shape. Fix this by pairing hand-written mocks with a contract test, covered in the next section, so a shape change in the real service is caught automatically.
- Relying on one big end-to-end suite as the only place integration problems are caught, which makes the suite slow and makes failures hard to localize to one service. Fix this by pushing as many checks as possible down into contract and integration tests, keeping the end-to-end layer to a small number of critical journeys.
Contract Testing Between Services
When two microservices talk over HTTP or a message queue, the riskiest failures rarely happen inside either service. They happen in the gap between them: a field the consumer expects but the provider stopped sending, a type that quietly changed from a string to a number, an endpoint that moved. Contract testing closes that gap without needing both services running together.
A contract is a recorded agreement about the shape of a request and the shape of a response: which fields exist, their types, and sometimes example values. The consumer team writes a test against a mock of the provider, and that test produces a contract file. The provider team then replays every interaction in that contract against their real service, outside of any consumer, and the test fails the moment the real response no longer matches what the consumer expects.
This is different from end-to-end testing, where both services are deployed and a request flows through the whole chain. Contract tests run fast, in isolation, and they tell you exactly which side broke the agreement. A consumer-driven approach, where the consumer defines what it needs and the provider verifies against that, keeps the contract honest: the provider cannot change behavior the consumer actually depends on without the test noticing.
The hard part is not writing the first contract. It is keeping it in sync as the API evolves over months, across teams who may not sit near each other. That requires a shared place to store contracts, a way to know which version of a contract each service version satisfies, and a habit of running verification on every build rather than occasionally.
Writing a Consumer-Driven Contract
In a consumer-driven workflow, the team that calls an API writes the first draft of the contract, because they are the ones who know exactly which fields they read and which they ignore. Using a tool like Pact, the consumer test sets up a mock provider, states what it expects for a given request, and asserts its own code handles the mocked response correctly. Running that test produces a contract file describing the interaction.
That file is then published somewhere both teams can reach it, commonly a Pact Broker or a similar shared store. The provider team pulls the latest contract and runs a verification step against their real, running service: for each recorded interaction, the broker replays the request and checks the actual response against what the consumer asked for. If a required field is missing or a type changed, verification fails before the mismatch reaches production.
The benefit of starting from the consumer side is that the contract never asks for more than is actually used. A provider is free to add new fields, rename internal data it does not expose, or restructure parts of its response the consumer never reads, all without breaking a single test. Only the fields and behaviors a consumer actually depends on are locked down, which keeps contracts small and keeps the provider's freedom to evolve as wide as possible.
Keeping Contracts in Sync as the API Evolves
A contract written once and never revisited becomes a lie within a few sprints. The practical discipline is running provider verification on every build of the provider, not just when someone remembers, so a breaking change is caught the same day it is written rather than weeks later. Most contract tooling can be wired into a pipeline step that fails the build on a broken verification, exactly like a unit test suite.
Versioning matters as much as the test itself. A contract should be tagged with the consumer version and, ideally, the environment it is heading to, so a provider team can ask a tool-specific question like "is it safe to deploy this provider version given every contract currently deployed in production." This is sometimes called a can-i-deploy check, and skipping it is one of the most common ways teams end up with a green pipeline and a broken integration anyway.
When an API change is genuinely breaking, the healthy pattern is versioning the endpoint or adding the new field alongside the old one for a deprecation window, giving every consumer time to update its own contract before the old shape disappears. Communicating a planned breaking change to consumer teams before it ships, rather than after a failed verification, turns contract testing from a safety net into a conversation that happens early.
const { PactV3, MatchersV3 } = require('@pact-foundation/pact');
const { like, string } = MatchersV3;
const provider = new PactV3({
consumer: 'OrderService',
provider: 'InventoryService',
});
describe('fetching stock level', () => {
it('returns the stock for a known SKU', async () => {
provider
.given('SKU ABC123 has stock')
.uponReceiving('a request for stock level')
.withRequest({
method: 'GET',
path: '/stock/ABC123',
})
.willRespondWith({
status: 200,
body: {
sku: string('ABC123'),
quantity: like(42),
},
});
await provider.executeTest(async (mockServer) => {
const res = await fetch(`${mockServer.url}/stock/ABC123`);
const data = await res.json();
expect(data.quantity).toBeDefined();
});
});
});
A consumer test for an order service that depends on an inventory service. It defines the exact interaction it needs, runs against a mock, and produces a contract file the inventory team can later verify against their real service.
# Run on the provider's CI pipeline after deploying to a test environment
pact-broker can-i-deploy \
--pacticipant InventoryService \
--version $GIT_SHA \
--to-environment production
# Fails the build if any consumer contract is not yet verified
# against this provider version
A pipeline check that asks the broker whether the provider version about to be deployed has satisfied every contract from every consumer currently relying on production, preventing a deploy that would break an integration.
Tips
- Start contracts from the consumer side so you only lock down fields the consumer actually reads, leaving the provider free to change everything else
- Run provider verification on every provider build, not on a schedule, so a broken contract is caught the day it happens
- Tag each published contract with the consumer version and target environment so a can-i-deploy style check can block an unsafe deploy
- Keep contract tests fast and isolated: no real database, no real network calls to a third service, just the one interaction being described
Common pitfalls
- Treating a contract test as a full integration test and asserting business logic inside it: a contract only checks shape and presence of fields, deeper behavior belongs in other test levels
- Letting contracts go stale by publishing them once and never re-verifying as the provider changes, which turns a safety net into a false sense of security
Integration Testing Against Real Dependencies
Unit tests tell you that a function behaves correctly in isolation, but microservices fail most often at their edges: a SQL query that works against an in-memory stub but breaks against a real Postgres, a message that serializes differently than the consumer expects, or a downstream HTTP call that times out under real network conditions. Integration testing against real dependencies closes that gap by running your service against an actual database, message broker or collaborating service, rather than a hand-written fake.
The practical way to do this without turning every test run into a fragile, shared staging environment is to spin dependencies up as disposable containers for the duration of the test suite, then tear them down. Each test run gets a clean Postgres, Kafka, Redis or RabbitMQ instance, started fresh, seeded with known data, exercised, and discarded. This keeps tests reproducible (no leftover state from a previous run), fast to reset (a fresh container beats manually truncating tables), and safe to run in parallel across a CI matrix.
This section covers how to structure these tests so they are fast enough to run on every pull request, how to manage test data and container lifecycle, and how to avoid the common trap of tests that pass locally but flake in CI because of timing, port conflicts or leftover volumes.
The goal is not to replace unit tests, but to add a layer that unit tests structurally cannot provide: confidence that your service and its real dependency agree on the contract between them, including the parts a mock would quietly let slide, like column types, index behavior, message ordering guarantees and connection pool exhaustion under load.
Using Containers to Model Real Dependencies
A container image for Postgres, Kafka or Redis is close enough to production to catch the bugs a mock cannot: wrong column types, missing indexes, encoding mismatches, or a message schema that serializes differently than your test double assumed. The key design decision is lifecycle: do you start one container per test, per test file, or once for the whole suite?
Per-test containers give perfect isolation but are slow, since spinning up a database can take a few seconds each time. Per-suite containers are fast but require you to clean up state between tests, usually by wrapping each test in a transaction that rolls back, or by truncating tables in a teardown hook. A common middle ground is one container per test file, reused across the tests in that file, with each test responsible for inserting only the data it needs and querying by a unique key so tests don't collide.
Libraries built for this purpose, such as Testcontainers (available for Java, Node, Python, Go and others), manage the container lifecycle for you: pulling the image, waiting for the service to report healthy, exposing a randomly assigned host port so tests never collide on a fixed port, and tearing the container down when the test process exits, even if a test crashes. This removes an entire class of flaky test caused by a fixed port already being in use on a shared CI runner.
For message queues, the same principle applies but the assertion is different: instead of querying a table, you publish a message and assert that a consumer processed it correctly, often by polling an output topic or checking a side effect with a short timeout rather than a fixed sleep.
Testing Against a Real Collaborating Service
Databases and queues are relatively easy to containerize because they ship official images. A collaborating microservice is trickier: do you run the real thing, or a lightweight stand-in that honors its contract?
When the collaborating service is simple to start, maybe it's your own team's service with its own Docker image, running the real thing in a container alongside your service under test gives the highest fidelity: real HTTP responses, real status codes, real latency characteristics. This is the right choice for a small number of critical downstream calls, such as an auth service your whole system depends on.
When the real service is heavy, owned by another team, or itself depends on dependencies you don't want to spin up, a contract-respecting stand-in is more practical: a lightweight HTTP server, started in-process or in its own container, that returns fixtures matching the real service's documented response shapes. The important discipline here is keeping those fixtures honest. A stand-in that nobody updates when the real service's API changes becomes worse than no test at all, because it gives false confidence. Pairing this approach with a periodic check against the real service's actual responses, even manually, keeps the fixtures trustworthy.
Either way, treat the dependency's address as configuration, not a hardcoded constant, so the same test code runs against a container in CI and against a real staging instance when you need to debug a failure that only reproduces there.
const { GenericContainer } = require('testcontainers');
const { Client } = require('pg');
let container;
let client;
beforeAll(async () => {
container = await new GenericContainer('postgres:16')
.withEnvironment({ POSTGRES_PASSWORD: 'test', POSTGRES_DB: 'orders' })
.withExposedPorts(5432)
.start();
client = new Client({
host: container.getHost(),
port: container.getMappedPort(5432),
user: 'postgres',
password: 'test',
database: 'orders',
});
await client.connect();
await client.query('CREATE TABLE orders (id SERIAL PRIMARY KEY, status TEXT)');
});
afterAll(async () => {
await client.end();
await container.stop();
});
test('creates an order with pending status', async () => {
await client.query("INSERT INTO orders (status) VALUES ('pending')");
const res = await client.query('SELECT * FROM orders');
expect(res.rows).toHaveLength(1);
expect(res.rows[0].status).toBe('pending');
});
Starts a disposable Postgres container with Testcontainers, connects to it using the port Docker assigned, runs a real SQL insert and query, then tears the container down after the test file finishes. No fixed port, no shared database, no leftover state between CI runs.
# docker-compose.test.yml
version: '3.8'
services:
kafka:
image: confluentinc/cp-kafka:7.6.0
environment:
KAFKA_BROKER_ID: 1
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
ports:
- '9092:9092'
# run the dependency, then the integration suite, then tear everything down
docker compose -f docker-compose.test.yml up -d
npm run test:integration
docker compose -f docker-compose.test.yml down -v
An alternative to per-test container libraries: a docker-compose file dedicated to tests, started before the suite and stopped with -v to remove volumes afterward, useful when several tests in the same CI job need to share one running broker.
Tips
- Let the container library assign a random host port instead of hardcoding one, so tests never collide on a CI runner that happens to be running two jobs at once.
- Wrap each test in a transaction and roll it back at teardown when you need many fast tests against one shared container, rather than paying the startup cost per test.
- Wait for a real health check (a successful query, a broker's ready endpoint) rather than a fixed sleep before running tests, since container startup time varies between machines and CI providers.
Common pitfalls
- Sharing one long-lived database between test runs: leftover rows from a previous run silently change the outcome of the next one. Start from a known, empty state every time, either a fresh container or a transaction rollback.
- Asserting on a message queue immediately after publishing, before the consumer has had time to process it: this produces tests that pass locally and flake in CI. Poll for the expected side effect with a short timeout instead of asserting immediately or sleeping a fixed amount.
Service Virtualization and Test Doubles
When a service under test depends on another service that is slow, flaky, rate-limited, or simply does not exist yet in a testable form, you need a stand-in. These stand-ins are broadly called test doubles, a term that covers several distinct techniques: stubs, mocks, fakes, and fully virtualized services. Picking the right one matters because each makes a different trade-off between realism, speed, and the strength of the guarantee it gives you.
A stub is the simplest form: a canned response returned regardless of what was sent in. Stubs answer the question 'what does my code do when the dependency returns X?' They are cheap to write and fast to run, but they do not verify that your code called the dependency correctly.
A mock goes further: it not only returns a canned response but also records how it was called, and the test asserts on that interaction (was this endpoint hit exactly once, with this payload?). Mocks answer 'did my code talk to the dependency the way it should have?' Overusing mocks couples your tests tightly to implementation details, so they are best reserved for verifying a genuinely important side effect, like confirming a payment request was sent.
A virtualized service sits a level above both: instead of replacing a single function call, it replaces an entire network service with something that behaves like the real one over HTTP, including latency, error codes, and stateful behavior across multiple calls. Tools like WireMock, Mountebank, and Prism let you record or hand-author these virtual services and run them in CI, giving every team a dependency that behaves consistently without needing the real thing deployed.
The right choice depends on scope: unit tests usually want stubs or mocks at the code boundary; integration and contract tests usually want a virtualized service that talks real HTTP.
Stubs vs Mocks: Verifying State vs Verifying Behavior
The clearest way to separate a stub from a mock is to ask what the test actually checks. A stub-based test is a state test: you call your function, the stub hands back a fixed value, and you assert on the state or output your function produced afterward. The stub itself is never inspected. This style keeps tests resilient to refactoring, because it does not care how many times or in what order the dependency was called, only that the final behavior is correct.
A mock-based test is a behavior test: after calling your function, you assert directly on the mock, checking that a specific method was invoked, with specific arguments, a specific number of times. This is valuable when the side effect itself is the point of the test, such as confirming an order-cancelled event was published exactly once, since there may be no other observable state to check.
A common pitfall is reaching for a mock by default. Behavior tests are more brittle: a harmless refactor that calls the same dependency in a different order, or batches two calls into one, can break a mock-based test even though the externally visible behavior is unchanged. A good rule of thumb is to default to stubs and fakes, and promote something to a mock assertion only when the interaction itself, not just its result, is a requirement worth protecting. Libraries like Sinon.js, unittest.mock in Python, and Jest's jest.fn() support both styles, so the discipline has to come from the test author, not the tool.
Virtualizing a Whole Service with WireMock
Stubs and mocks replace a single function or client call inside your process. A virtualized service replaces the dependency at the network boundary: your service still makes a real HTTP request, it just lands on a fake server instead of the real one. This is the right tool when you are testing a service in isolation but still want to exercise your actual HTTP client, your retry logic, your timeout handling, and your error-parsing code, none of which an in-process stub touches.
Tools such as WireMock, Mountebank, and Hoverfly let you define a virtual service declaratively: given a request matching this path and method, respond with this status code, this body, and after this delay. Because the virtual service runs as a real server, you can also simulate failure modes that are hard to trigger against a real dependency on demand, like a 503, a slow response near your timeout threshold, or a connection reset. This is often more valuable for microservices testing than functional correctness, since many production incidents in distributed systems come from how services behave when a neighbor degrades rather than when it works perfectly.
A pitfall here is letting the virtual service drift from the real one. If the real service changes its response shape and nobody updates the stub definitions, your tests keep passing while production breaks. Pairing virtualization with a contract test, such as a Pact contract shared between the consumer and provider teams, keeps the virtual service honest by verifying it still matches what the real provider actually returns.
const sinon = require('sinon');
const { getUserDiscount } = require('./pricing');
const userService = require('./userServiceClient');
test('applies discount for premium users', () => {
// Stub: just controls the return value, not inspected
sinon.stub(userService, 'getTier').returns('premium');
const result = getUserDiscount('user-42');
expect(result).toBe(0.15);
sinon.restore();
});
test('publishes a cancellation event exactly once', () => {
// Mock: the call itself is the thing under test
const publish = sinon.mock(eventBus).expects('publish').once().withArgs('order.cancelled');
cancelOrder('order-99');
publish.verify();
sinon.restore();
});
The first test uses a stub to control a dependency's return value and checks the resulting output. The second uses a mock to assert that a specific side-effecting call happened exactly once with the right arguments, which is the detail that actually matters for that behavior.
const { WireMock } = require('wiremock-captain');
const wireMock = new WireMock('http://localhost:8080');
beforeEach(async () => {
await wireMock.register(
{ method: 'GET', endpoint: '/accounts/42/balance' },
{ status: 503, body: { error: 'temporarily unavailable' } }
);
});
test('retries once then surfaces a clear error on repeated 503s', async () => {
await expect(fetchBalanceWithRetry('42')).rejects.toThrow('balance service unavailable');
});
A virtual service built with WireMock simulates the account service returning a 503, letting the test verify the calling service's retry and error-handling logic without needing the real account service to be unreliable on demand.
Tips
- Default to stubs and fakes for most tests, and reserve mock-style call assertions for interactions that are themselves a requirement, like confirming an event was published.
- Use a virtualized service, not an in-process stub, whenever you need to test real network behavior: timeouts, retries, HTTP status handling, or malformed responses.
- Keep stub and virtual-service definitions close to the consumer's test suite but review them whenever the provider's API changes, ideally enforced by a contract test.
Common pitfalls
- Writing brittle tests full of mock call assertions for every dependency, which breaks on harmless refactors; fix by checking final state or output instead of every intermediate call wherever behavior itself isn't the requirement.
- Letting a virtualized service's responses silently diverge from the real dependency over time, so tests pass while production fails; fix by backing the stub definitions with a shared contract test against the real provider.
Data Consistency Across Service Boundaries
In a monolith, a single database transaction can guarantee that an order, its inventory deduction, and its payment record either all succeed or all roll back together. Microservices break that guarantee apart: each service typically owns its own database, so a single business operation like 'place an order' now touches three or four independently-deployed services, each with its own storage, its own failure modes, and its own network hop in between. There is no distributed ACID transaction tying them together in most real systems, because two-phase commit across services is slow, fragile, and couples services tightly in exactly the way microservices are meant to avoid.
Instead, teams rely on patterns like the saga pattern (a sequence of local transactions, each with a compensating action if a later step fails), eventual consistency (the system converges to a correct state within some time window rather than instantly), and outbox/event-driven updates (a service publishes a domain event after committing locally, and other services react asynchronously). Testing this world means testing time, not just outcome: did the system end up consistent, and did it stay internally believable (no lost messages, no double-charges, no orphaned records) while it got there?
This section covers how to design tests that verify eventual consistency without becoming flaky, and how to verify that compensating transactions actually undo partial work when a saga step fails partway through. We also look at the operational signals (dead-letter queues, reconciliation jobs, idempotency keys) that a thorough test suite should exercise, not just the happy path where every service responds instantly and correctly.
Testing Eventual Consistency Without Flaky Tests
The single biggest mistake teams make when testing eventually-consistent flows is asserting on state immediately after triggering an action. If service A publishes an event and service B consumes it asynchronously, checking service B's database right after calling service A's API is a race condition, not a test. The fix is to poll with a bounded timeout and a sensible interval, treating 'became consistent within N seconds' as the actual contract under test, and failing clearly if that bound is exceeded rather than hanging forever.
A second issue is treating eventual consistency tests as pure black boxes. It helps to also assert on the mechanism: was the event actually published to the broker, did the consumer acknowledge it, did a retry happen if the first delivery failed. Tools like a message broker's admin API, or application logs correlated by a trace ID, let you distinguish 'the data is wrong' from 'the data isn't here yet.'
It also matters to test the window itself, not just the end state. A good consistency test suite includes at least one scenario that reads during the inconsistency window and confirms the system behaves sensibly there, for instance showing an order as 'processing' rather than silently returning stale or contradictory data. Finally, keep these tests isolated from unrelated services' latency: use dedicated test topics or tenant IDs so one slow test doesn't pollute another's wait condition, and always tear down consumed messages between test runs so retries from a previous test don't leak into the next one's assertions.
Verifying Sagas and Compensating Transactions
A saga succeeds when every step commits; it also has to succeed, in a different sense, when a step fails partway through and prior steps must be undone. Testing only the happy path of a saga misses the harder and more valuable case: injecting a failure at each step in turn and confirming the compensating actions actually run and actually restore the prior state, not just that an error was logged.
Concretely, this means standing up (or mocking) each downstream service so you can force a specific step to fail, for instance having the payment service return a decline after inventory has already been reserved, and then asserting that the inventory reservation is released rather than left dangling. Each compensating action should be tested in isolation too: a 'release inventory' compensator should be idempotent, because sagas often retry compensations after a crash, and running it twice must not double-release stock that was never actually held twice.
Idempotency keys deserve their own tests: send the same 'charge card' command twice with the same key and confirm the customer is charged once, not twice. Also test the saga's own crash recovery: if the orchestrator process restarts mid-saga, does it resume from its last known step, or does it restart the whole saga and risk duplicate side effects? A saga test suite that only checks 'all steps succeeded' or 'all steps failed and compensated' is incomplete; the valuable tests are the ones where some steps succeeded, one failed, and compensation had to partially unwind real state.
// Jest test: polling for eventual consistency with a bounded timeout
async function waitForCondition(checkFn, { timeoutMs = 5000, intervalMs = 200 } = {}) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
const result = await checkFn();
if (result) return result;
await new Promise(r => setTimeout(r, intervalMs));
}
throw new Error(`Condition not met within ${timeoutMs}ms`);
}
test('order status becomes CONFIRMED after payment service processes the event', async () => {
const order = await orderService.create({ items: ['sku-123'], amount: 4200 });
// Trigger async flow: order service emits 'OrderCreated', payment service consumes it
await expect(
waitForCondition(async () => {
const current = await orderService.get(order.id);
return current.status === 'CONFIRMED' ? current : null;
}, { timeoutMs: 8000, intervalMs: 250 })
).resolves.toMatchObject({ status: 'CONFIRMED' });
});
Polls the order's status instead of asserting immediately, giving the asynchronous payment consumer a bounded window to react before the test fails.
// Jest test: a saga's compensating action must be idempotent
test('releasing an inventory reservation twice does not over-release stock', async () => {
const sku = 'sku-123';
await inventoryService.reserve(sku, { qty: 2, reservationId: 'res-1' });
// Simulate the saga compensator firing twice, e.g. after an orchestrator crash + retry
await inventoryService.release({ reservationId: 'res-1' });
await inventoryService.release({ reservationId: 'res-1' });
const stock = await inventoryService.getStock(sku);
expect(stock.reserved).toBe(0);
expect(stock.available).toBe(stock.total); // not over-credited
});
Calls the same compensating action twice to confirm it is idempotent, which matters because saga orchestrators commonly retry compensations after a crash.
Tips
- Always give eventual consistency tests a bounded timeout with polling, never a fixed sleep, so tests fail fast on real bugs instead of hanging or passing by luck.
- Test compensating actions in isolation for idempotency, since a saga orchestrator will retry them after crashes and duplicate side effects are a common production bug.
- Correlate logs and events with a trace ID across services so a failing consistency test tells you which hop was slow or lost, not just that the final state was wrong.
Common pitfalls
- Asserting on downstream state immediately after an async trigger, which produces flaky tests that pass or fail depending on machine load; fix this by polling with a timeout tied to the system's real SLA for consistency.
- Only testing the saga's happy path and never injecting a mid-saga failure, which leaves the compensating transactions, the part most likely to have bugs, completely untested.
End-to-End Testing of a Complete User Journey
In a microservices system, no single service can tell you whether the business actually works. End-to-end (E2E) tests exist to answer one question: can a real user, hitting the real edge (a browser, a mobile client, a public API), walk through a complete journey and get the outcome they expect, with every service, queue, and database involved exactly as it would be in production?
That power comes at a cost. E2E tests are slow to run, expensive to maintain, and the hardest layer to keep stable, because they depend on the correctness and availability of everything underneath them. The practical answer is not to avoid them, but to be deliberate: pick a small number of journeys that genuinely matter to the business (sign up, place an order, process a refund), keep that layer deliberately thin compared to your unit and integration suites, and build in the discipline to survive the flakiness that comes from coordinating many real, independently deployed services.
A useful mental model is the testing pyramid: hundreds or thousands of unit tests, a healthy layer of integration and contract tests, and only a handful of E2E journeys at the top. If your E2E suite is testing feature variations, edge cases, or error handling, that work almost always belongs at a lower layer where it runs faster and fails more clearly. E2E tests should answer 'does the journey work end to end', not 'does every branch of the journey work'.
This section covers how to choose which journeys deserve E2E coverage, how to keep the layer from growing out of control, and how to handle the inherent instability of testing a distributed system as a whole.
Choosing the Journeys Worth Testing End to End
Start from the business, not the architecture. List the handful of flows that, if broken, would stop revenue, damage trust, or create legal risk: a customer completing checkout, a user resetting a password and regaining account access, an order moving from placement to fulfillment. These are the journeys where a failure is expensive enough to justify the cost of an E2E test that spans every service involved.
Resist the temptation to add a journey just because it crosses an interesting number of services, or because a team wants visibility into their corner of the system. Service-level correctness belongs in that service's own unit and contract tests. An E2E journey earns its place only when it exercises a path a real user takes, with a real business outcome at the end, across service boundaries you do not otherwise verify.
A good practice is to name each candidate journey in plain business language before writing a single line of test code: 'a new user signs up, verifies their email, and lands on their dashboard' rather than 'auth-service calls notification-service and user-service'. If you cannot describe the journey that way, it is probably not a true end-to-end journey, it is an integration test wearing an E2E test's clothes.
Review the list periodically. As the system evolves, some journeys stop mattering and new ones appear; a stale E2E suite that nobody has pruned becomes slow, flaky, and ignored. Treat the list of E2E journeys as a living, small, curated set, not a growing archive.
Keeping the Layer Thin and Taming Flakiness
Every E2E test you add is a recurring tax: it runs slower than a unit test, it touches infrastructure you do not fully control in CI, and it fails for reasons that have nothing to do with the code under test, an expired certificate, a slow downstream dependency, a shared test environment another team just redeployed. The way to keep this tax affordable is to keep the number of E2E journeys small and to make each one as deterministic as the environment allows.
Practical measures that help: run E2E journeys against isolated, seeded data rather than shared fixtures that other tests or people can mutate mid-run; add explicit waits for real conditions (an element appearing, a response arriving) rather than fixed sleeps; and retry a failed run once before treating it as a real failure, since a single flaky step should not block a deployment on its own.
When a step in a saved journey breaks because the application changed, you do not want to rewrite the whole journey, only repair the part that broke. This is the kind of targeted repair xtest's test agents perform automatically: when a saved step stops working, the test agent takes over from that step alone and saves the repair. Whatever tooling you use, aim for that same principle: isolate the blast radius of a UI or API change to the smallest part of your journey's automation.
Finally, treat an E2E failure as a signal to investigate, not to immediately rerun until green. A pattern of intermittent failures on the same step usually points to a real timing or data problem worth fixing at the source.
const { test, expect } = require('@playwright/test');
test('customer can complete checkout end to end', async ({ page }) => {
await page.goto('https://shop.example.com');
await page.getByRole('link', { name: 'Wireless Headphones' }).click();
await page.getByRole('button', { name: 'Add to cart' }).click();
await page.getByRole('link', { name: 'Cart' }).click();
await page.getByRole('button', { name: 'Checkout' }).click();
await page.getByLabel('Card number').fill('4242424242424242');
await page.getByLabel('Expiry').fill('12/29');
await page.getByLabel('CVC').fill('123');
await page.getByRole('button', { name: 'Place order' }).click();
await expect(page.getByText('Order confirmed')).toBeVisible({ timeout: 15000 });
const orderNumber = await page.getByTestId('order-number').textContent();
expect(orderNumber).toMatch(/^ORD-\d{6}$/);
});
A single Playwright test covering a complete checkout journey across the storefront, cart, and payment services, waiting for a real confirmation state rather than a fixed delay, and asserting on the actual business outcome: an order number.
async function waitForOrderStatus(apiBaseUrl, orderId, expectedStatus, timeoutMs = 20000) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
const res = await fetch(`${apiBaseUrl}/orders/${orderId}`);
const order = await res.json();
if (order.status === expectedStatus) return order;
await new Promise((r) => setTimeout(r, 500));
}
throw new Error(`Order ${orderId} did not reach status ${expectedStatus} in time`);
}
A polling helper used in an E2E journey to wait for an asynchronous downstream service (for example, a fulfillment worker) to catch up, avoiding fixed sleeps that cause flaky failures when a service is briefly slower than usual.
Tips
- Keep a written, short list of the business journeys covered end to end, and review it every quarter so it reflects what the business actually depends on today.
- Seed each E2E run with its own isolated data (a freshly created user and order) instead of sharing fixtures across tests, so one test's side effects cannot flake another.
- Replace fixed sleeps with waits for a real condition, such as an element appearing or an API returning the expected state, to cut down on timing-related flakiness.
- Run the E2E suite against an environment as close to production as practical, but isolated enough that another team's deploy cannot break your run mid-test.
Common pitfalls
- Letting the E2E suite grow to cover every feature variation: push edge cases and error handling down to unit and integration tests, and reserve E2E journeys for the few paths where a real user's outcome is on the line.
- Treating every E2E failure as a real bug without checking for environmental causes first: a pattern of failures tied to timing, shared data, or a flaky downstream dependency should be fixed at the source rather than papered over with blanket retries.
Versioning and Backward Compatibility
In a microservices architecture, services evolve independently and deploy on their own schedules. This independence is powerful, but it creates a real risk: a team ships a change to their service's API, and somewhere else in the system a consumer that was never updated breaks in production. Versioning and backward compatibility testing exists to catch that risk before it reaches users.
The core idea is simple: a new version of a service's API should either stay compatible with everything that currently depends on it, or any breaking change should be rolled out through a deliberate, tested process rather than a surprise. This means testing isn't just "does my new code work," it's "does my new code still satisfy every contract that other teams are relying on."
There are two broad categories of change to think about. Additive, non-breaking changes include adding a new optional field to a response, adding a new endpoint, or adding a new optional query parameter. These should never break an existing consumer if clients are built correctly (ignoring unknown fields rather than failing on them). Breaking changes include removing a field, renaming a field, changing a field's type or meaning, changing required parameters, or changing error response formats. These require a coordinated migration strategy.
Testing strategy needs to cover both the producer side (does this service still honor its existing contracts) and the consumer side (does my client correctly handle both old and new response shapes). This section covers consumer-driven contract testing as the primary technique, along with API versioning schemes and safe rollout patterns like dual-running old and new versions side by side.
Consumer-Driven Contract Testing
Consumer-driven contract testing flips the usual testing direction. Instead of the API producer guessing what shape of response consumers need, each consumer publishes a contract describing exactly the requests it makes and the responses it expects. The producer then runs those contracts as tests against its own codebase, in CI, before every deploy.
The workflow typically looks like this: a consumer team writes a test using a tool like Pact that records the interactions their client makes with a mock of the provider. This generates a contract file (a JSON pact file) describing request and response pairs. That contract is published to a broker. The provider team's CI pipeline then pulls all contracts that reference their service and verifies each one against the real running service. If a response no longer matches what a consumer expects, the provider's build fails immediately, long before a deploy would have broken that consumer.
This approach has a major advantage over end-to-end integration tests across every service: it scales. You don't need to spin up ten dependent services to test one API change; you only need the contracts. It also surfaces exactly which consumer would break and why, which makes the fix targeted rather than a mystery debugging session involving multiple teams.
The discipline this requires is cultural as much as technical: consumer teams must keep their contracts current, and provider teams must treat a broken contract verification as a release blocker, not a warning to ignore. Without that discipline, the contracts silently drift out of date and stop providing real protection.
API Versioning Strategies and Safe Rollouts
When a breaking change is genuinely unavoidable, the question becomes how to roll it out without forcing every consumer to update in lockstep. A few common strategies:
URI or header versioning. Expose the old and new API shapes simultaneously, either through a version segment in the path (/v1/orders, /v2/orders) or through a version header. Old consumers keep calling v1 while new consumers adopt v2, and the old version is only retired once telemetry shows no traffic is hitting it.
Expand-contract (parallel change). Rather than renaming a field outright, add the new field alongside the old one (expand), update the producer to populate both, let every consumer migrate to the new field at their own pace, and only remove the old field once nothing reads it anymore (contract). This avoids a flag-day cutover where every team has to deploy at the same moment.
Dual-running and shadow traffic. Run the new version of a service alongside the old one, routing a copy of production traffic to the new version without acting on its response, and compare outputs. This surfaces compatibility gaps under real traffic patterns before the new version takes over fully.
Testing each of these strategies means writing tests that assert old consumers keep working against the old version for as long as it's live, that the producer correctly serves both shapes during the overlap window, and that a deprecation timeline is actually enforced (an automated check that fails if a deprecated field is still being read past its sunset date is far more reliable than a reminder in a wiki page).
const { PactV3, MatchersV3 } = require('@pact-foundation/pact');
const { like, eachLike } = MatchersV3;
const provider = new PactV3({
consumer: 'OrderDisplayService',
provider: 'OrdersAPI',
});
describe('Orders API contract', () => {
it('returns an order with the expected shape', async () => {
await provider
.given('an order with id 123 exists')
.uponReceiving('a request for order 123')
.withRequest({ method: 'GET', path: '/v1/orders/123' })
.willRespondWith({
status: 200,
body: {
id: like('123'),
status: like('shipped'),
items: eachLike({ sku: like('ABC-1'), quantity: like(2) }),
},
});
await provider.executeTest(async (mockServer) => {
const res = await fetch(`${mockServer.url}/v1/orders/123`);
const body = await res.json();
expect(body.status).toBe('shipped');
});
});
});
A consumer-side Pact test using Jest. It defines the exact request the OrderDisplayService makes and the response shape it expects, using matchers (like, eachLike) so the contract checks structure and types rather than exact values. The generated contract file is published to a broker for the Orders API team to verify against their real service.
// Provider-side verification, run in the OrdersAPI's CI pipeline
const { Verifier } = require('@pact-foundation/pact');
new Verifier({
provider: 'OrdersAPI',
providerBaseUrl: 'http://localhost:4000',
pactBrokerUrl: 'https://pact-broker.internal.example.com',
consumerVersionSelectors: [{ mainBranch: true }],
stateHandlers: {
'an order with id 123 exists': async () => {
await seedOrder({ id: '123', status: 'shipped', items: [{ sku: 'ABC-1', quantity: 2 }] });
},
},
publishVerificationResult: true,
providerVersion: process.env.GIT_SHA,
}).verifyProvider().then(() => console.log('All consumer contracts satisfied'));
The provider's verification step, run as part of the Orders API's own CI build. It pulls every contract published against the main branch of each consumer, seeds the described state, and checks the live service against every consumer's expectations before the build is allowed to pass.
Tips
- Treat a failed contract verification as a release blocker in CI, not a warning someone will look at later; a contract that nobody enforces stops protecting anyone within a few weeks.
- Prefer additive changes (new optional fields, new endpoints) over renaming or removing fields; most compatibility breaks come from changing something that already existed rather than adding something new.
- Automate the deprecation timeline: write a test or monitoring check that fails the build once a deprecated field or endpoint is still being used past its announced sunset date, rather than relying on a team remembering to remove it.
- Version your error responses too, not just success responses; consumers often parse error bodies for retry logic, and changing an error shape breaks them just as badly as changing a success shape.
Common pitfalls
- Relying only on end-to-end tests across every dependent service to catch compatibility breaks. This is slow, flaky, and only tells you something broke, not why, whereas consumer-driven contracts pinpoint the exact expectation that failed.
- Letting published contracts go stale because no one owns keeping them current. A contract written once and never updated as the consumer's real usage changes gives false confidence; schedule contract reviews alongside normal API review, not as an afterthought.
- Removing an old API version based on a deploy date rather than actual traffic. Always check real traffic or logs for the old version before retiring it; a consumer can still be calling a 'deprecated' endpoint long after everyone assumed it had migrated.
- Changing field types silently, such as turning a string id into a numeric one. Clients that parse the field strictly will break even though the field technically still exists, so compatibility tests need to check types, not just field presence.
Building a Complete Microservices Test Strategy
A test pyramid is only a diagram until you decide, concretely, what runs when. The real work of a microservices test strategy is wiring the layers (unit, component, contract, integration, and end-to-end) into a pipeline that gives fast feedback on every commit while still catching the defects that only show up when real services talk to each other.
The guiding question for every layer is: what does this catch, and what does it cost? Unit and component tests are cheap and should run on every commit, in seconds. Contract tests are nearly as cheap and belong on every commit too, because a broken contract is exactly the kind of bug that integration and end-to-end tests catch far too late and far too expensively. Integration tests against real dependencies, and end-to-end flows across several services, cost more time and more infrastructure, so they tend to run less often: before merging to the main branch, or before a release, rather than on every push.
The strategy fails if the pipeline is simply 'run everything, every time.' That approach either takes so long that people stop waiting for it, or it gets skipped under deadline pressure, which quietly turns a comprehensive pyramid into an untested one. A working strategy stages the pyramid explicitly: fast, deterministic checks gate the commit; slower, broader checks gate the merge or the release.
For end-to-end coverage specifically, you want flows that exercise the system the way a user actually would, without hand-maintaining brittle scripts for every service change. xtest lets you describe a test in plain English in Test Lab, pick a device, and watch an AI test agent carry it out, which is one way to keep that top layer from becoming the part of the pipeline nobody wants to touch.
Staging the Pipeline: Commit Gate vs Release Gate
Split your pipeline into at least two gates, and name them in your CI config so the intent is obvious to anyone reading the YAML a year from now.
The commit gate runs on every push and every pull request. It should contain only unit tests, component tests with test doubles, and consumer-driven contract tests. All of these are deterministic, run without spinning up other services, and should complete in well under five minutes. If a change breaks the commit gate, the developer who pushed it gets the failure before they have context-switched to something else, which is the whole point.
The release gate runs less often: on merge to main, on a schedule, or just before a deployment. It contains the integration tests that hit real databases and message brokers, the contract verification against the provider's actual code, and the end-to-end flows that walk through two or more services together. This gate can take longer, because by the time it runs, a slower feedback loop is an acceptable trade for broader coverage.
A common refinement is a third, lighter gate for the deployment pipeline itself: a small smoke suite that runs against the freshly deployed environment to catch configuration or environment problems that no earlier gate could see, since those only exist once the service is actually running somewhere.
Keep the gates independent in your CI tool so a slow release-gate run never blocks someone else's unrelated commit from getting fast feedback.
Keeping the Whole Suite Fast Enough to Trust
A test suite that nobody waits for is a test suite nobody runs voluntarily, so speed is not a nice-to-have, it is part of the strategy. Three techniques do most of the work.
First, parallelize aggressively within a gate. Unit and component tests are usually independent of each other, so splitting them across workers by file or by historical duration turns a ten-minute serial run into a two-minute parallel one. Most test runners and CI systems support this natively.
Second, cache what doesn't change. Dependency installation, Docker image layers, and compiled contract definitions can all be cached between runs so the pipeline spends its time running tests, not rebuilding the world around them.
Third, keep the slow layer small on purpose. The end-to-end layer should cover the handful of flows that genuinely need multiple real services working together: a checkout, a signup, a payment. Everything else that looks like it needs an end-to-end test is usually better served by a contract test plus a component test, which run in a fraction of the time and fail with a much clearer message about which service is at fault.
Track the suite's running time the same way you track its pass rate. If the commit gate creeps past five minutes, treat that as a regression to fix, not a cost of doing business, because once people start skipping the wait, the gate stops protecting anything.
name: ci
on: [push, pull_request]
jobs:
commit-gate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- name: Unit and component tests
run: npx jest --maxWorkers=4 --testPathPattern='unit|component'
- name: Consumer contract tests
run: npx jest --testPathPattern='contract/consumer'
release-gate:
needs: commit-gate
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
services:
postgres:
image: postgres:15
env:
POSTGRES_PASSWORD: test
ports: ['5432:5432']
steps:
- uses: actions/checkout@v4
- run: npm ci
- name: Integration tests against real database
run: npx jest --testPathPattern='integration'
- name: Provider contract verification
run: npx jest --testPathPattern='contract/provider'
- name: End-to-end flows
run: npx playwright test e2e/checkout.spec.ts e2e/signup.spec.ts
A two-gate GitHub Actions pipeline. The commit-gate job runs on every push with only fast, dependency-free tests. The release-gate job only runs on main and spins up a real Postgres instance for integration tests, verifies provider contracts, and runs a small, deliberately short list of end-to-end flows.
Tips
- Name your CI jobs after what they gate (commit-gate, release-gate), not after the tool that runs them, so the strategy stays visible in the config itself.
- Measure and publish the commit gate's running time alongside its pass rate; treat a creeping runtime as a bug, not a fact of life.
- Put contract tests on the commit gate, not the release gate, since the whole value of a contract test is catching an incompatibility before it reaches integration or end-to-end tests.
Common pitfalls
- Running the entire pyramid on every commit: it feels thorough but it trains the team to stop waiting for CI, which defeats fast feedback entirely. Split into commit and release gates instead.
- Letting the end-to-end layer grow to cover edge cases that belong lower in the pyramid: a single failing end-to-end test rarely tells you which service is at fault, while a failing contract or component test usually does.
Exercises
Exercise 1: Mapping a Test Pyramid onto a Small System
In this exercise you design a test pyramid for a small system of three services: an order service, an inventory service and a notification service. The order service accepts a new order, checks the inventory service to confirm stock, and if stock is available, calls the notification service to email the customer a confirmation. Your task is to decide, for each of the four layers covered in this course (unit, contract, integration, end-to-end), what specifically would be tested at that layer for this system, and to write down at least two concrete test cases per layer. For the unit layer, focus on logic that lives entirely inside one service, such as how the order service calculates a total or validates an order's fields. For the contract layer, write down the shape of the request the order service sends to the inventory service, and the shape of the response it expects back, as if you were writing a contract test between the two. For the integration layer, describe what a test would need running (which containers, which databases) to check the order service really talks correctly to a real inventory service. For the end-to-end layer, describe exactly one full journey worth testing across all three services, and explain why you chose that one journey over the others.
- Sketch the three services and the calls between them on paper or in a simple diagram.
- List at least two unit test cases for the order service's own logic, with no network call involved.
- Write the request and response shape you would expect a contract test to check between the order service and the inventory service.
- Describe the environment (containers, test data) an integration test would need to check the order service against a real inventory service.
- Choose one complete user journey to cover at the end-to-end layer and justify why it is the most important one to test across the whole system.
Expected outcome: A written test pyramid for the three-service system, with at least two named test cases at the unit layer, a clear request/response contract described for the contract layer, a description of the environment needed for an integration test, and one justified end-to-end journey, showing a clear understanding of what question each layer of the pyramid is meant to answer.
Exercise 2: Writing a Contract Test with a Consumer-Driven Approach
In this exercise you write a contract test between two services using a consumer-driven approach, where the consumer of an API defines the expectations and the provider is checked against them. Using Jest and a contract testing library such as Pact, set up a simple consumer test for a service that calls a GET /inventory/:sku endpoint expecting a JSON body with sku and available fields. The consumer test should generate a contract file describing the expected request and response. Then write the matching provider verification step that checks the real inventory service actually returns a response matching that contract. Run the consumer test first to confirm it generates a contract, then run the provider verification against a locally running version of the inventory service to confirm the two sides agree. Finally, deliberately change the inventory service's response to rename the available field to inStock, and confirm the provider verification step now fails, demonstrating that the contract test catches a breaking change before it reaches another team.
- Write a consumer test with Jest and a contract testing library that calls GET /inventory/:sku and defines the expected response shape.
- Run the consumer test and confirm it produces a contract file describing the request and expected response.
- Write a provider verification test that replays the contract's requests against a locally running inventory service and checks the real responses match.
- Run the provider verification and confirm it passes against the current version of the inventory service.
- Change the inventory service's response field name from available to inStock, rerun the provider verification, and confirm it now fails, demonstrating the contract catches the breaking change.
Expected outcome: A passing consumer test, a generated contract file, a provider verification step that passes against the correct inventory service response, and the same verification step failing once the response shape is deliberately broken, demonstrating that a contract test catches an API shape change before it reaches production.
Quiz
1. Why does a traditional, monolith-shaped test pyramid tend to fall short in a microservices architecture?
- Because unit tests run slower in a distributed system
- Because it has no layer that checks whether two independently deployed services agree on the shape of what they exchange
- Because microservices cannot be unit tested at all
- Because end-to-end tests are not possible across multiple services
Show answer
B. Because it has no layer that checks whether two independently deployed services agree on the shape of what they exchange
A traditional pyramid assumes the only boundary to test is inside one deployable. Microservices add a new boundary, between independently deployed services, which a plain unit-test-to-end-to-end-test pyramid has no dedicated layer for. Contract testing fills that gap.
2. What question does a contract test answer that a unit test, using a hand-written mock of another service, does not?
- Whether the service's own internal logic is correct
- Whether the service starts up fast enough
- Whether the consumer and the provider actually agree on the current shape of the request and response between them
- Whether the database schema is correct
Show answer
C. Whether the consumer and the provider actually agree on the current shape of the request and response between them
A hand-written mock reflects whatever shape its author assumed at the time it was written, and can quietly drift out of date. A contract test explicitly checks that the provider's real behavior still matches what the consumer expects, catching drift that a static mock would miss.
3. Why should the end-to-end layer of a microservices test pyramid be kept thin, covering only a small number of journeys?
- Because end-to-end tests are not allowed in continuous integration
- Because running many real services together is slow and more prone to flakiness than testing each service or boundary separately
- Because end-to-end tests cannot find any real defects in a microservices system
- Because only the provider service needs to be tested end to end
Show answer
B. Because running many real services together is slow and more prone to flakiness than testing each service or boundary separately
Standing up multiple real services together for a test run is inherently slower and more fragile than testing a single service or a single boundary between two services, so the end-to-end layer should be reserved for the handful of journeys that matter most rather than used to cover every path.
4. In the three-service example (order, inventory, notification), which of the following would best belong at the integration testing layer rather than the unit testing layer?
- Checking that the order service correctly applies a discount for large quantities
- Checking that the order service, running against a real inventory service in a container, correctly receives a stock confirmation
- Checking that an order's required fields are validated before it is accepted
- Checking that a total is calculated correctly for a single item
Show answer
B. Checking that the order service, running against a real inventory service in a container, correctly receives a stock confirmation
The first, third and fourth options test logic entirely inside the order service, with no network call, which belongs at the unit layer. The second option exercises a real network call to a real, running inventory service, which is what defines the integration layer.
5. What is the main risk of relying only on one large end-to-end suite to catch every integration problem in a microservices system, rather than also using contract and integration tests?
- End-to-end tests cannot be automated
- The suite becomes slow and prone to failures unrelated to the code under test, which teams tend to ignore or skip under deadline pressure, defeating its purpose
- End-to-end tests require no infrastructure at all
- Contract tests are always slower than end-to-end tests
Show answer
B. The suite becomes slow and prone to failures unrelated to the code under test, which teams tend to ignore or skip under deadline pressure, defeating its purpose
An end-to-end suite that must start every service and dependency for every run tends to be slow and flaky for reasons that have nothing to do with the actual code change being tested, and a flaky suite that nobody trusts often gets skipped, which removes the safety net it was meant to provide.