Chapter 15 of 27 · Part 7: Testing

Integration, contract and end-to-end tests

FTGO's unit tests pass, yet releases still break where a service meets its database, its broker or another service. This chapter climbs the pyramid to test those seams cheaply, keeps slow end-to-end tests to a few, and moves the last checks into production.

key idea / coordinator service / good path in progress / watch out problem / failure neutral

Where we are

In chapter 14 we gave every FTGO service a pyramid of fast unit tests with stubs and mocks, and made the tests a gate in each service's pipeline. That left one problem open: unit tests check each service against its own assumptions, not against its real database, its broker or the services it talks to.

This chapter

How does FTGO check that a service works with real infrastructure and still agrees with its neighbors, without one huge test environment? By the end you can write integration, contract and component tests, keep end-to-end tests to a few journeys, and choose safe ways to test in production.

Test the adapters against real infrastructure

Unit tests replaced the database and the broker with doubles. The code that talks to them, the adapters, was never run for real.

Problem

Order Service's unit tests use an in-memory repository, and they all pass. In production, the ORM mapping for the new deliveryInstructions field points at a column that does not exist, so saving any order with instructions fails.

Solution · Integration tests for adapters

Test each adapter against the real technology it wraps, one adapter at a time. Start the real database in a container, and check that what the adapter writes, it can read back.

Persistence integration test Start DB MySQL in Docker Txn 1: save new Order Txn 2: load findById() Assert fields match Unit tests only use objects in memory. This proves the ORM mapping works against a real database.

A persistence test saves an Order in one transaction and loads it with findById() in a second, so the test proves the round trip through MySQL rather than an object cached in memory.

A wider variant tests a whole microservice through its real HTTP interface, with no mocks. In a side example from FlixTube (chapter 26), Jest starts MongoDB with Docker Compose, loads known test data called a fixture, sends a request with Axios and checks the reply.

Integration test of one microservice Compose up starts MongoDB Load fixture known records HTTP request Axios to the API Assert check the reply The fixture helper empties the test database first: never aim it at production.

These tests are slower than unit tests, but one test covers a lot of code and finds problems that hide between modules.

Cost

Containers make the suite slower and need a fixture helper that empties the database, which must never point at production. And the adapters that call other services are still tested against stubs that nobody checks against the real thing.

Check each seam with a shared contract

This is the gap chapter 14 ended on: both sides of a seam can be green while the seam is broken.

Problem

The API gateway's OrderServiceProxy is tested against a stub that returns {"orderId": ..., "state": "APPROVED"}. The Ordering team renames state to status. Order Service's tests pass, the gateway's tests pass against the old stub, and the order page breaks in production.

Solution · Contract tests

Write down the interaction once, as an example: a sample request and the expected response, or a sample message. Generate a test for the provider and a stub for the consumer from that same example. If both sides pass against the same contract, they agree on the API.

For each interaction style from chapter 14, the contract holds something different: an HTTP request and response (API gateway → Order Service), one event (Order Service → Order History), or a command and its reply (Order Service → Kitchen Service).

For REST, a tool such as Spring Cloud Contract turns the contract for GET /orders/{id} into two things: a provider test that calls OrderController (with its services mocked), and a WireMock stub server. The gateway's OrderServiceProxy test calls findOrderById(), which sends GET /orders/1223232 to WireMock instead of the real Order Service, and checks the fields in the contract's JSON reply.

REST contract tests Contract GET /orders/{id} Spring Cloud generates + stubs Provider test controller + mocks Consumer stub WireMock server If both sides pass against the same contract, they agree on the API.

The same idea works for messaging. For publish/subscribe, the consumer test asks a messaging stub to publish the contract's OrderCreated event and checks that the handlers update the DAO. On the provider side, a generated test checks that Order Service publishes an event that matches the contract.

Publish/subscribe contract: consumer side Test Messaging stub Event handlers Mock DAO trigger event label OrderCreated addOrder() verify eventually Provider side: a generated test checks Order Service publishes an event matching the contract.

For asynchronous request/response, the consumer sends a CreateTicket command, the stub checks it against the contract input and replies with the contract's CreateTicketReply. On the provider side, Kitchen's command handler gets the input message and must send the output message.

Async request/response contract: consumer side Test KitchenProxy Messaging stub send CreateTicket command message match contract input CreateTicketReply assert reply Provider side: Kitchen's command handler gets the input message and must send the output message.
Cost

Contracts are more files to keep in step. And if the provider writes them, they describe what the provider thinks it offers, not what each consumer relies on. A schema has the same blind spot: it catches a missing field, but not a field whose meaning changed.

Let consumers write the contract: CDCs and Pact

The question shifts from "is the API well formed?" to "will my change break someone who uses it?"

Problem

Order Service changes the order total from dollars to cents. The schema still says total is a number, so every schema check passes. Kitchen Service and the API gateway now show a 16-dollar order as 1,633 dollars. This is a semantic break: the behavior changed, the shape did not.

Solution · Consumer-driven contracts (CDCs)

Each consumer team writes down what it expects from the provider, as examples. The provider runs every consumer's expectations in its own build, alone, with its own dependencies stubbed. A failure names the consumer that would break, before release.

Contracts from two consumers run against one producer Gateway tests Kitchen tests Order build runs both sets, alone Accounting stub Each consumer writes its expectations. The producer runs them on every build. A failure shows exactly which consumer would break.

The consumer team sends its contracts to the provider, for example as a pull request to the provider's repository. If the provider build fails, the change would break a consumer: fix it, or talk.

Pact is a popular CDC tool. The consumer test runs against a Pact mock server that records the expectations into a JSON Pact file; the same mock server works as a local stub for the consumer. The Pact Broker stores versions of the file, and the producer build verifies them. The broker also records when each contract was last verified and which services depend on which. Spring Cloud Contract is an alternative, but it suits an all-JVM stack.

How Pact works Consumer test expectations Pact file JSON contract Pact Broker stores versions Producer build verifies the file The mock server that writes the Pact file also works as a local stub for the consumer.
CheckCatchesScope
SchemaStructural breaks (field removed)Tiny
Consumer-driven contractSemantic breaks (behavior changed)One service, like a component test
End-to-end testBoth, plus wiring problemsMany services, slow

Good practice is for people from both teams to write the contracts together. A CDC is a record of a conversation, and a broken contract is the cue for the next one.

When trust is low: CDCs need good communication. For a third party you cannot talk to, keep a few larger tests around that component. For a public API with thousands of consumers, play the consumer yourself or work with a subset of them.
Cost

CDCs need teams that talk and a broker to run. They check each message, one at a time. They do not check that Order Service, as a whole, does the right thing with a sequence of requests and replies.

Test one whole service: component tests

Unit tests check classes, integration tests adapters, contracts messages. Nothing yet checks the behavior of the service as a whole.

Problem

Creating an order runs a saga: Order Service sends AuthorizeCommand to Accounting over Kafka and waits for the reply. Each piece has passing tests. But after a refactoring, Order Service never moves the order to APPROVED, because the reply handler is no longer subscribed to the right channel.

Solution · Component (service) tests

Test one whole service as a black box, through its API, with every service it calls replaced by a stub. If the test breaks, the fault is in that service.

Component tests are acceptance tests for one service, so they are often written in near-English with Gherkin. Cucumber runs each scenario as a real test, and each step maps to a test phase.

Acceptance tests written in Gherkin Gherkin step Given a valid consumer and card When I place an order Then the order is APPROVED And OrderAuthorized is published Test phase Setup Execute Verify Verify Cucumber runs these near-English scenarios as real tests.

Behind the steps, the test makes the Accounting stub reply with success (Given), posts the order (When), and then reads the order and checks that OrderAuthorized was published (Then). Order Service is real; its saga partners are stubs that reply over Kafka.

Component test for Order Service Step defs Order svc Kafka Accounting stub reply success (Given) POST /orders (When) AuthorizeCommand success reply GET /orders/{id} check OrderAuthorized Order Service is real. Its saga partners are stubs that reply over Kafka.

The service under test can run in two ways:

Two ways to run a component test In-process Same JVM as the test In-memory DB and messaging Fast and simple Does not test the real build Out-of-process Service runs in Docker Real MySQL and Kafka Tests what you ship Slower, more complex

Out-of-process tests check what you actually ship: Docker Compose builds the service, starts it with MySQL and Kafka, runs the Cucumber scenarios and stops the containers.

For REST dependencies, a smart stub server saves writing a stub per service. mountebank is one: a small server you program over HTTP. You create imposters, each listening on a port with a protocol (HTTP, HTTPS, TCP or SMTP) and the replies to send, and one instance can stand in for many services. It cannot fake message brokers, which is where contract tools such as Pact help.

A service test with a smart stub Test Order svc mountebank create imposter "Accounting" GET order 123 GET payment, order 123 canned reply: AUTHORIZED order + payment status The stub answers the same way whether it is called 0, 1 or 100 times.

For an event-driven service there is also a cheaper in-memory variant: feed a fake event in, let the real logic run against fake I/O, and check the state change and the events published. It is fast and deterministic, which makes it good for idempotency and error paths (chapter 6).

Component test with fakes Feed an event in, check the state change and the events published. Fake event OrderCreated Service real logic, fake I/O Assert state and output Fast and deterministic. Good for idempotency and error paths (lesson 06).

Put together, each event-driven service needs these tests:

TestScopeBroker and database
UnitOne class or function in a layer.None
ComponentThe whole service, in memory.Fakes or in-memory stand-ins
Half-breed integrationThe service with real infrastructure.Real broker and database, other services faked
ContractThe messages between two services.None needed
Cost

Out-of-process component tests are slower and more complex than unit tests, and in-process ones do not test the real build. Each still checks one service with stubbed neighbors, so no test so far shows a customer placing, changing and cancelling an order across the whole system.

Prove a few key journeys end to end

At the top of the pyramid sit the tests that run everything together.

Problem

Before a big launch, the product owner asks: does a customer's whole journey work, through the gateway, Order, Kitchen and Accounting? Every lower test passed, but none of them ran those services together.

Solution · A few user-journey tests

Write end-to-end tests for only a few key journeys, and make each one a whole journey rather than one test per action. One test that places, revises and cancels an order needs less setup than three separate tests.

One end-to-end user journey Place order APPROVED, $16.33 Revise order +2 samosas, $20.97 Cancel order CANCELLED One journey test instead of three separate tests means less setup and fewer slow tests.

Gherkin and Cucumber work here too. Even for FTGO such a test takes minutes, so push every check you can down the pyramid.

For a web app, the journey test drives the real UI. In the FlixTube side example, Docker Compose boots a cut-down app and Playwright drives the browser, seeing the app the way a customer does. A small REST service loads fixtures for the tests.

Playwright against an app running under Docker Compose Playwright headless Gateway serves the UI Metadata video records MongoDB test database Fixture API load test data docker compose up --build A cut-down app is enough. A small REST service loads fixtures for the tests.

A test loads a fixture, opens a page, then asserts what it shows, for example that the video list has two entries. Playwright runs headless, can try several browsers, and gives good reports, so it fits a CI pipeline via npm test. It can also mock the backend to test a frontend alone, though that is then not truly end-to-end.

Fast loops: live reload (nodemon plus Docker volumes) restarts services as you edit, so you do not rebuild the whole application per change. Also test production mode locally now and then, so Dockerfile problems do not pile up.
Cost

End-to-end tests are slow, brittle and hard to debug. With one app and one team that is tolerable. With many teams it starts to undo the independent deployment that microservices were for.

Why end-to-end suites hurt, and how to shrink them

Once end-to-end tests exist, every team wants its change checked by them.

Problem

FTGO adds a shared end-to-end stage that every service pipeline feeds into. Which versions of the other services should the Order build test against? The stage takes an hour, a Kitchen test is flaky, and while it is red no team can deploy.

Fan-in: many pipelines share one end-to-end stage Order build Kitchen build Accounting build Gateway build Shared e2e stage all services deployed Deploy Which versions of the others do you test with? One slow stage now blocks every team.
PitfallWhy it hurts
Flaky and brittleMore moving parts mean failures that say nothing about the feature. People rerun and stop trusting the suite.
SlowSuites of a day, or six weeks for a regression run. Failures surface after you have moved on.
Great pile-upA broken stage blocks check-ins, changes accumulate and each release gets riskier. The fix is a faster suite.
Metaversion"These versions work together" slides into one version number and deploying everything at once.
No independent testingShared test environments and shared suites force teams to coordinate. High performers test on demand.

Ownership is a problem too. When everyone adds tests, nobody owns the failures. A dedicated test team is far from the code, and service owners wait on it. Shared ownership works but is rare and needs discipline. At a certain organizational scale you need to move away from cross-team end-to-end tests.

Solution · Treat end-to-end tests as training wheels

Keep them while the other safeguards are weak, and shrink them as contracts and production checks mature. Build end-to-end confidence from many small checks: each service validates itself and its seams, so a failing flow usually maps to one component that can check that condition by itself.

Training wheels for releases E2E net slow but safe Add contracts schemas + CDCs Add prod checks canary, monitoring Shrink E2E only what is left Do not drop them before you know what you would lose.
QuestionBest tool
Will my change break a consumer?Consumer-driven contract
Does the service work with neighbors stubbed?Component test
Does one key user journey work?A few end-to-end tests
Is it working for real users right now?Testing in production (next)
Cost

Do not drop end-to-end tests before you know what you would lose. And however good the tests, a pre-production environment never matches live traffic, real data and real load.

Test where the software really runs

More pre-production testing has diminishing returns. A distributed system has too many surprises to drive the chance of failure to zero.

Problem

A new version of Kitchen Service passes every test. At the Friday dinner peak, real order events include a field combination that no fixture had, and Kitchen stops creating tickets. Every restaurant is affected at once, and the rollback takes 20 minutes.

Solution · Testing in production

Separate deployment from release. Deploy the new version, smoke-test it before anyone uses it, release it to a few users as a canary, and widen only if it is healthy. Synthetic transactions and chaos tests keep running after release.

TechniqueWhat happensReal users affected?
Ping / health checkIs the instance alive?No
Smoke testAutomated check of a new deployment, before releaseNo
Synthetic transactionFake user with known input and expected output, run regularly; keep test data out of reportsNo (fake data)
Canary releaseNew version for a small slice, widen if healthyA few
Feature flagCode ships dark and is turned on gradually, or off in seconds; remove old flagsAs many as you choose
A/B testTwo versions side by side, see which performs betterSplit
Parallel run or shadowingOld and new both process the input; users see one result, you compareNo
Chaos engineeringInject faults, e.g. Chaos Monkey stops VMs (chapter 18)System under stress

Event-driven services make shadowing easy. Run the new Kitchen version in its own consumer group: both groups receive every order event, the shadow's output is compared but not used, and external effects such as emails are switched off.

Shadowing with a separate consumer group A new version reads the same events but its output is not used. Topic order events Live v1 group: live Shadow v2 group: shadow Compare no side effects Both groups get every event. Disable external effects such as emails in the shadow.

A canary then sends a small share of real traffic to the new version, widening step by step while you watch error rate, latency and consumer lag.

Canary release and feature flag Send a small share of traffic to the new version, and switch behavior by flag. 5% canary watch error rate 25% watch latency and lag 100% retire old version A feature flag turns behavior off without a redeploy, so rollback takes seconds.

There are two ways to reduce production pain: fail less often (a longer mean time between failures, MTBF) or recover faster (a shorter mean time to repair, MTTR). Teams that pour effort into pre-production tests often neglect the monitoring and fast rollback that recovery needs.

Two ways to reduce production pain Lower failure rate (MTBF) More pre-production tests Never reaches zero Diminishing returns Faster recovery (MTTR) Very fast rollback Good monitoring Canary limits the damage Teams that pour effort into tests often neglect monitoring and recovery.
Make it safe: use fake users and data, and watch side effects. One company ran tests against live ordering and a pile of washing machines arrived at head office. If the product idea is unproven, skipping pre-production tests can even be sensible. Rollout mechanics are in chapters 19 and 21; rewinding offsets and the outbox are in chapter 6.
Cost

Some users see a bug first, shadows add load and risk duplicate side effects, and flags pile up. All of it needs good monitoring (chapter 17). These techniques check that features work; they say little about how fast FTGO is, or how it behaves when a dependency fails.

Performance and robustness tests

Speed, capacity, accessibility and security are often called non-functional requirements. Cross-functional requirements is a better name: they emerge from work across the whole system.

Problem

In the monolith, showing an order was one database query. Now it is a call from the gateway to Order Service, which calls Restaurant and Delivery. Each call is fast on its own, but at dinner peak one slow link in the synchronous chain slows every order page, and nobody measured it before launch.

Cross-functional requirements Speed Latency page response time Capacity Users how many at once Access Accessibility usable by all Safety Security customer data Follow the pyramid: a load test finds the bottleneck, a small test keeps it fixed.
Solution · Performance and robustness tests

Test performance early, not just before launch, on a production-like setup with load that ramps up. Re-create failures on purpose to check that the resilience code works.

A useful performance test Prod-like setup data and machines Ramp up users gradually Watch latency at each load level Compare vs target or last Run a subset daily and a bigger set weekly. Then actually read the numbers.

Many of these can only be fully checked in production, but tests show whether you are heading the right way. Follow the pyramid here too: a load test finds the bottleneck, and a small test keeps it fixed. Without a target from your SLOs, fail the build when results move too far from the previous run.

Robustness tests re-create failures, for example an artificial time-out between a service and its stub, to check that retries and circuit breakers behave. They are worth it for shared code such as a service mesh default.

Cost

Production-like environments and data are expensive, and the numbers are useless unless someone reads them. And tested code is still not production-ready: it also has to be secure and correctly configured in every environment.

Practices in this chapter

PracticeProblem it solvesWhat it costs
Integration tests for adaptersORM mappings and queries that only fail against the real databaseSlower tests; containers and fixtures to manage
Contract testsBoth sides of a seam pass their own tests while the seam is brokenContracts to keep in step with the code
Consumer-driven contracts (Pact)Semantic breaks that schemas missTeams must talk; a broker to run
Component (service) testsA service whose pieces pass but whose behavior is wrongSlower; neighbors are still stubs
A few end-to-end journey testsNo check that key journeys work across servicesSlow, flaky, hard to debug, couples teams
Shrinking the end-to-end suiteA shared stage that blocks every teamNeeds mature contracts and production checks first
Testing in production (smoke, synthetic, canary, flags, shadowing)Pre-production never matches live traffic and dataSome users may see bugs; needs monitoring and fast rollback
Performance and robustness testsNetwork chains that are slow under load; resilience code that never ranProduction-like setups; results someone must read

Recap

Quick check

One REST contract (GET /orders/1223232 → 200 + JSON) is used in two ways. What are they?
Show answer

It generates a provider-side test that calls OrderController, and it configures a WireMock stub that the API gateway's proxy test calls instead of the real Order Service.

Order Service starts sending the order total in cents instead of dollars. The schema still says the field is a number, and every pipeline is green. What breaks, and which test would have caught it before production?
Show answer

Every consumer that reads the total, such as Kitchen Service and the API gateway, now shows wrong amounts. Schemas only check structure. A consumer-driven contract holds a sample response with the value the consumer expects, and Order Service's build runs it on every change, so the build would have failed and named the consumer.

How can FTGO try a new Kitchen Service version on real order events without affecting restaurants?
Show answer

Run it as a shadow in its own consumer group, with side effects disabled, and compare its output with the live version. Then release it as a canary to a small share of traffic, behind a feature flag for a fast rollback.

Still open

FTGO's services are now tested from unit to production. But tested code is not yet production-ready: every request must be authenticated and authorized, services must trust each other safely, and each service needs its configuration and credentials in every environment.

Next: 16 Security, configuration and the chassis →