Skip to content

Microservices testing: contracts, isolation and on-demand environments

B2Bnetwork team · · 6 min

Testing and quality

In brief

Microservices are tested mainly at the level of a single service: unit tests, component tests of the service running in isolation with a real database in a container and stubs for its neighbors, and contract tests that keep it compatible with other services. End-to-end tests across the whole system are few and cover only key processes. An on-demand environment for each pull request replaces the shared test environment, and checks after deployment catch what cannot be reproduced before production.

What changes compared with a monolith

In a monolith, integration tests ran in one process and a release covered the whole system. With microservices, each service has its own release cycle and bugs move to the boundaries between services.

MonolithMicroservices
where bugs arisein the logic and the databasealso at the boundaries: message format, API version, timeouts
who releasesone team, one releasemany teams, independently
test environmentone, with the full systema shared environment becomes a bottleneck
end-to-end testslow but stableslow and brittle, because it depends on many versions at once
production failurethe whole system or nothingpartial: one service slows down and drags others with it

The most common mistake after moving to microservices is keeping the monolith's test strategy and relying on end-to-end tests in a shared environment. Then one service at the wrong version blocks several teams' testing, and independent releases stop being independent. Whether microservices pay off at all is discussed in Microservices: when they pay off.

Test layers for a single service

A microservices strategy shifts the weight to tests the service team runs on its own, without waiting for anyone:

  1. Unit tests of domain logic: fast, with no network or database.
  2. Component tests of the whole service: the running service, a real database and message broker in containers, and neighboring services replaced by stubs. The test sends a request to the service API or a message to a queue and checks the response, the database state and the emitted events.
  3. Contract tests: they verify that the service sends and accepts exactly what its consumers expect.
  4. A few end-to-end tests for processes whose failure costs the most, for example placing an order and paying for it.

The proportions between the layers are covered in The test pyramid in practice. For microservices, the pyramid has a particularly wide middle: component tests give the most confidence for a reasonable run time.

Isolation: real dependencies in containers, stubs for neighbors

You test a service with its own dependencies in their real form and with neighboring services through stubs. The Testcontainers library starts a container with a database, a message broker or another component for the duration of the test and removes it afterwards. The test runs on the same database version as production, not on an in-memory database that behaves differently with transactions and data types.

Neighboring services are replaced by HTTP stubs or service virtualization. A stub lets you check situations that are hard to trigger on a real system: a response after 30 seconds, a 503 error, truncated JSON. That is exactly where microservice bugs live: no timeout, endless retries, a circuit breaker that never opens. External system stubs are covered in more depth in Service virtualization in testing.

Contracts between services

A stub has one weakness: it can lie. If the consumer team writes a stub that returns a field `kwota` and the provider renames it to `amount`, both sides' tests pass and production fails. Contract tests close that gap.

In consumer-driven contracts, the consumer records in a test which responses it expects. The test produces a contract file that goes to a contract broker. The provider verifies in its own pipeline that its service meets the contracts of all its consumers. Pact supports this for both HTTP calls and messages sent through a broker. Before deployment, the pipeline asks the broker whether the new version is compatible with the consumer versions already in production. If not, the deployment stops.

Details and pitfalls, such as contracts that are too strict or too loose, are covered in API contract testing. This is the approach in the case study on API and contract test automation in an online banking microservices program, where contracts that block incompatible deployments replace testing in a shared environment once per release.

On-demand environments

An on-demand (ephemeral) environment is created automatically for a pull request and disappears when it is closed. In Kubernetes it is usually a separate namespace with the new version of the service, its database and its dependencies. Other services run either at their production versions or are replaced by stubs.

To make it work, you need:

  • fast provisioning: container images ready, configuration in the repository, start-up time measured in minutes,
  • seed data: a script that creates the accounts, products and dictionaries the tests need, without a production copy,
  • cleanup: automatic removal and a time-to-live limit, because forgotten environments quickly drive up the cloud bill,
  • a clear version list: you know which neighbor versions the change was tested against.

On-demand environments do not fully replace a shared integration environment, but they take most of the traffic off it. End-to-end and performance tests stay there.

Checks after deployment

Some microservice bugs only show up under real traffic: a rare combination of versions, an exhausted connection pool, a cascade of delays. So testing also moves past deployment:

  • canary releases: the new version gets a small percentage of traffic, and error and response time metrics decide whether to widen it,
  • synthetic tests: scripts walk through key paths in production every few minutes,
  • feature toggles: new behavior can be switched off without redeploying,
  • distributed tracing: a request ID travels through all services, so you can see where a delay arose.

This approach is covered in more depth in Shift-left and shift-right. B2Bnetwork engineers set up such a strategy as part of test automation: from component tests and contracts to pipeline gates that block incompatible deployments.

Questions and answers

Do you have to give up end-to-end tests with microservices?

No, but their role changes. A few tests remain for the highest-risk processes, run in an integration environment or after deployment. Most of the confidence comes from component and contract tests the team runs on its own. Hundreds of end-to-end tests across dozens of services usually mean long and unstable runs.

How much does an on-demand environment per pull request cost?

The cost depends on the number of services in the environment, how long it lives and how many neighbors are replaced by stubs. The biggest savings come from automatic removal when the pull request closes and a time-to-live limit. It is worth comparing with the cost of teams waiting for a shared environment today.

Where to start when a company already has dozens of microservices and only end-to-end tests?

With contracts between the services that break each other most often. The history of incidents and defects usually points to a few such pairs. In parallel, teams add component tests for the services that change most often. Cut back end-to-end tests only once the new layers catch the same bugs.

How do you test communication through queues and events?

The same way as an API: a component test checks that after receiving a message the service saves the right state and emits the right events, and a contract test guards the message format between producer and consumer. Also check redelivery of the same message and messages arriving out of order.

What it looks like in a project

Planning testing for your project? Talk to a test manager.

Let's talk

Read more: Testing and quality

All in Testing and quality →