Video in progress

Staff 🌱 Spring

How do you build a test strategy for a multi-service system, and how do you verify the contract between services?

By the pyramid: lots of fast unit tests, integration tests inside each service with real dependencies (Testcontainers), and between services contract tests (Pact or Spring Cloud Contract) instead of full e2e. E2E only for a few critical business flows.

📖 Answer

Why more E2E is bad: bringing up 20 services in one environment is slow and flaky, when a test fails it's hard to tell which service is at fault, and teams end up waiting for each other's deploys.

The layers:

  • Unit: domain logic, no Spring, in milliseconds.
  • Slice tests: @WebMvcTest, @DataJpaTest, for a single layer.
  • Service integration: @SpringBootTest + Testcontainers (database, Kafka), with external services stubbed by WireMock.
  • Contract: the agreement between services.
  • E2E: the 5-10 most important flows (sign-up, payment), in staging.
  • In production: synthetic monitoring and canaries.

How a consumer-driven contract (Pact) works:

  1. the consumer (say, checkout) writes in its own test what it expects from the provider, and a contract file is produced;
  2. the contract is uploaded to a broker;
  3. the provider (payment) verifies all consumers' contracts against itself in its own CI;
  4. can-i-deploy checks before deploy that this version is compatible with every consumer in the environment.

As a result, if the provider wants to remove a field, it learns before deploy that some consumer uses it.

The same goes for events: Kafka message schemas live in a Schema Registry with backward compatibility mode, and a breaking schema can't be registered.

Also watch the speed and reliability of the test suite. "Sometimes failing" tests kill the team's trust in tests, so fix them right away or quarantine them.