Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท Testing and Evolution

Testing Microservices

Test microservices without a giant test environment: the test pyramid, consumer-driven contract tests, fakes, component tests and a runnable contract checker.

In a monolith you can start the application and click through it. In a system of twenty services, "start everything and test it" means twenty deployments, twenty databases, a broker and a lot of waiting. Such end-to-end suites are slow, flaky and fail for reasons that have nothing to do with the change you just made. Teams that rely on them stop trusting their tests.

The way out is to test each service in isolation, quickly, and to test the agreements between services separately. This lesson shows the layers, the idea of consumer-driven contracts, how to use fakes instead of real neighbours, and what a component test is. You will run a contract checker and a component test yourself.

The test pyramid, adapted

The classic pyramid still holds: many fast tests at the bottom, few slow tests at the top. For microservices the middle gets an important addition.

Layers of tests

Unit One function or class. Milliseconds. Hundreds of them.
Component One whole service, neighbours replaced by fakes.
Contract Do provider and consumer still agree on the API?
End-to-end A handful of journeys across the real system.

The higher the layer, the slower, the flakier, and the fewer tests you want.

1 / 2

Unit tests cover business rules: how a discount is computed, whether an order total includes tax. They run in memory, in milliseconds.

Component tests start one service with its real code, its own real (often in-memory or containerised) database, and fake versions of every other service. They exercise the public API of that service as a black box and prove that routes, serialisation, persistence and configuration work together.

Contract tests check the shape of conversations between two services without running both. End-to-end tests run through the real, deployed system; keep only a few critical journeys, such as "place an order and pay".

Why integration between services breaks

Most production incidents in distributed systems do not come from a bug inside one service. They come from a mismatch: the provider renamed total to amount, the consumer still reads total, and both services pass all of their own tests. Neither team did anything wrong in isolation.

Unit tests cannot see this, because each service tests against its own assumptions. Component tests with hand-written fakes cannot see it either: the fake simply encodes the consumer's outdated belief. You need a way to compare the assumptions of one side with the reality of the other.

Consumer-driven contract tests

In a consumer-driven contract (CDC) approach, each consumer writes down exactly what it relies on: "I call GET /orders/:id and I need id (number), total (number) and status (string)". That list is the contract. It is published to the provider's pipeline (often via a broker such as Pact Broker or a shared repository).

The provider then runs every consumer's contract against its real implementation in CI. If a change would break any consumer, the provider's build fails before deployment, and the team knows exactly which consumer to talk to. Two details matter:

  • A contract states only what the consumer actually uses, not the whole response. The provider stays free to add fields or change everything the consumer ignores.
  • Consumers verify their own code against a generated fake of the provider built from the same contract, so the fake cannot drift away from the truth.

Tools such as Pact (many languages) and Spring Cloud Contract automate the file formats and verification. The core idea is small, and the stand-in below implements it in about forty lines. This stand-in is a simplified checker; real tools also cover HTTP methods, status codes, headers and message contracts.

Node.js A tiny consumer-driven contract checker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Provider v2 broke only billing: shipping never read total, and the added channel field hurt nobody. That is the big payoff of contracts built from usage: you learn exactly who is affected, instead of fearing every change.

Fakes and other test doubles

To test a service alone, replace its collaborators with test doubles. The vocabulary is worth knowing:

  • A stub returns canned answers: getPrice("sku-1") always returns 10.
  • A fake is a simplified but working implementation, such as an in-memory repository or a payment gateway that keeps a list of charges.
  • A spy records how it was called so a test can inspect the calls afterwards.
  • A mock is a spy with expectations built in ("fail if charge is not called exactly once").

Prefer fakes over mocks when you can. A fake has behaviour, so tests describe outcomes ("the order was declined and no stock stays reserved") instead of being glued to the sequence of internal calls, which makes them survive refactoring. For another service, a fake that is generated from a contract, or a simple in-process stub server, keeps the double honest.

A component test with fakes

The next example is a component test in miniature. The OrderService is the system under test. Its neighbours (payments and a repository) are injected, so the test can hand it a fake payment gateway that records charges and can be told to decline. A small test runner prints pass or fail.

Node.js Component test with a fake payment gateway

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Each test builds fresh fakes, so tests do not influence each other. Notice what the assertions check: HTTP-style status, saved state, and what the neighbour received. None of them cares how place is written inside. In a real component test the OrderService would run behind its real HTTP server and a real database, and the fake payments service would be a tiny HTTP stub. What is real here: the testing structure. What is a stand-in: everything runs in one process with no network.

Strategies that keep the suite healthy

  • Test the contract, not every combination. If providers and consumers verify contracts in CI, you do not need to deploy both to know they fit.
  • Make failure injection part of component tests. Have the fake time out, return 500, or answer slowly, and assert that your service degrades gracefully (Circuit Breakers, Bulkheads and Fallbacks).
  • Test events too. Messages have contracts as well: consumers should declare the event fields they read and providers should verify them, just like HTTP responses.
  • Keep a few smoke tests in production. After a deploy, a synthetic check ("create a test order") confirms that the real wiring works; combine with Deployment Strategies and CI/CD.
  • Make tests deterministic. Inject clocks and random sources instead of calling Date.now() directly, and never depend on another team's shared staging environment.

A suite made only of end-to-end tests looks safe and ends up ignored: it takes an hour, fails randomly, and nobody knows which service broke it. Invest in the lower layers first.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a consumer-driven contract describe?

    The consumer states just what it uses. That lets the provider change everything else freely and tells it exactly who a change would break.
  2. 2. Why prefer a fake over a mock in most tests?

    Tests tied to outcomes survive refactoring; tests tied to the exact sequence of calls break whenever the implementation changes.
  3. 3. What is a component test?

    It exercises routes, persistence and configuration together, but stays fast and reliable because other services are doubles.
  4. 4. The provider renames a field that no consumer reads. What do the contract tests report?

    Contracts are built from usage. A field nobody relies on can change without failing any contract.
  5. 5. Where should most of your tests live?

    The pyramid shape keeps feedback fast and failures easy to locate.

Summary

  • Test services in isolation with unit and component tests, and keep end-to-end tests to a few critical journeys.
  • Integration breaks come from mismatched assumptions, so verify the agreements between services with contract tests.
  • In consumer-driven contracts, each consumer publishes what it uses and the provider verifies all of them in CI.
  • Use fakes (working simplified implementations) and failure injection to test a service alone.
  • Test events and message formats like HTTP APIs, and keep tests deterministic.

Next: API Versioning and Evolving Contracts.