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
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.
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.
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.
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.
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.
These tests are slower than unit tests, but one test covers a lot of code and finds problems that hide between modules.
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.
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.
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.
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.
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.
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?"
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.
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.
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.
| Check | Catches | Scope |
|---|---|---|
| Schema | Structural breaks (field removed) | Tiny |
| Consumer-driven contract | Semantic breaks (behavior changed) | One service, like a component test |
| End-to-end test | Both, plus wiring problems | Many 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.
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.
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.
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.
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.
The service under test can run in two ways:
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.
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).
Put together, each event-driven service needs these tests:
| Test | Scope | Broker and database |
|---|---|---|
| Unit | One class or function in a layer. | None |
| Component | The whole service, in memory. | Fakes or in-memory stand-ins |
| Half-breed integration | The service with real infrastructure. | Real broker and database, other services faked |
| Contract | The messages between two services. | None needed |
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.
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.
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.
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.
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.
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.
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.
| Pitfall | Why it hurts |
|---|---|
| Flaky and brittle | More moving parts mean failures that say nothing about the feature. People rerun and stop trusting the suite. |
| Slow | Suites of a day, or six weeks for a regression run. Failures surface after you have moved on. |
| Great pile-up | A 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 testing | Shared 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.
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.
| Question | Best 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) |
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.
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.
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.
| Technique | What happens | Real users affected? |
|---|---|---|
| Ping / health check | Is the instance alive? | No |
| Smoke test | Automated check of a new deployment, before release | No |
| Synthetic transaction | Fake user with known input and expected output, run regularly; keep test data out of reports | No (fake data) |
| Canary release | New version for a small slice, widen if healthy | A few |
| Feature flag | Code ships dark and is turned on gradually, or off in seconds; remove old flags | As many as you choose |
| A/B test | Two versions side by side, see which performs better | Split |
| Parallel run or shadowing | Old and new both process the input; users see one result, you compare | No |
| Chaos engineering | Inject 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.
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.
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.
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.
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.
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.
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.
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
| Practice | Problem it solves | What it costs |
|---|---|---|
| Integration tests for adapters | ORM mappings and queries that only fail against the real database | Slower tests; containers and fixtures to manage |
| Contract tests | Both sides of a seam pass their own tests while the seam is broken | Contracts to keep in step with the code |
| Consumer-driven contracts (Pact) | Semantic breaks that schemas miss | Teams must talk; a broker to run |
| Component (service) tests | A service whose pieces pass but whose behavior is wrong | Slower; neighbors are still stubs |
| A few end-to-end journey tests | No check that key journeys work across services | Slow, flaky, hard to debug, couples teams |
| Shrinking the end-to-end suite | A shared stage that blocks every team | Needs mature contracts and production checks first |
| Testing in production (smoke, synthetic, canary, flags, shadowing) | Pre-production never matches live traffic and data | Some users may see bugs; needs monitoring and fast rollback |
| Performance and robustness tests | Network chains that are slow under load; resilience code that never ran | Production-like setups; results someone must read |
Recap
- Integration tests check each adapter against real infrastructure, such as a persistence round trip through MySQL.
- Contract tests turn one example of a request, event or command into a provider test and a consumer stub, and consumer-driven contracts (for example with Pact) also catch semantic breaks that schemas miss.
- Component tests run one whole service as a black box with its neighbors stubbed, in process or in Docker; event-driven services add in-memory and half-breed integration variants.
- End-to-end tests should cover only a few key user journeys, because they are slow, flaky and couple teams; shrink them as contracts and production checks mature.
- Testing in production separates deployment from release with smoke tests, synthetic transactions, canaries, feature flags and shadowing, and balances fewer failures (MTBF) with faster recovery (MTTR).
- Performance and robustness tests should run early and regularly, because splitting a system turns local calls into network chains.
Quick check
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.
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.
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.
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.