Video in progress

Strong Middle 🧪 Testing

How does consumer-driven contract testing work between microservices, and how does it differ from an ordinary integration test?

The consumer service writes down, as a contract, what request it sends to the provider and what response it expects. The provider is verified against those contracts in its own CI. That way, an API change that would break a consumer is caught in advance, without starting the two services together.

📖 Answer

The problem: order-service calls the GET /customers/{id} endpoint of customer-service and tests it with WireMock. The customer-service team renames the phone field to phoneNumber. Both services' tests are green, since each lives with its own assumptions. The bug only shows up on staging or in prod.

Contract testing closes this gap. Two main tools:

Pact (consumer-driven): the consumer test records the expected request and response, a pact file is produced when the test passes, and it's uploaded to the Pact Broker. In its own build, the provider takes all consumers' pacts from the broker and replays them against the real controller.

Spring Cloud Contract: contracts are usually written in Groovy/YAML in the provider's repository. From them, automatic tests are generated for the provider, and a WireMock stub JAR for the consumer.

request:
  method: GET
  url: /customers/42
response:
  status: 200
  headers: { Content-Type: application/json }
  body: { id: 42, phone: "+998901234567" }

The difference from an integration test: it doesn't fully verify that the services work together, only the agreement on the interface. It doesn't check business logic, data state or the network.

In practice the hardest part isn't the technology but the process: the provider team has to agree to stop the build when a contract breaks, and contracts have to be versioned. Pact's can-i-deploy command answers exactly this question before a deploy.