Contract testing

Senior Differentiator 4 min

On this page

The question

How do you test integrations between microservices without end-to-end tests?

30-second answer

With contract tests. The two sides agree on a contract for one API: this request gets this response. The consumer tests its client against a mock generated from the contract, and the provider replays the contract against its real service. Each runs in its own build, with neither deployed, so a breaking change fails fast. Pact and Spring Cloud Contract are the common tools.

Understand it

The consumer writes it, the provider verifies it

Step by step

The Order service test states what it needs: GET /customers/42 returns an id and a name. It runs against a Pact mock server, with no provider running.

Step 1 of 6
View as text

The Order service, the consumer, is on the left, with a Pact mock server below it. The Customer service, the provider, is on the right, with a Pact Broker below it. The contract sits across the bottom: the request and the response fields.

The Order service test states what it needs: GET /customers/42 returns an id and a name. It runs against a Pact mock server, with no provider running.

The test passes, so Pact writes the contract to a file: the request, and only the response fields this consumer really uses. The contract panel fills in.

The consumer build publishes the contract to a Pact Broker, tagged with its version, where the provider team can find it. An arrow goes from the contract to the broker.

The provider's build fetches the contract, sets up the state 'customer 42 exists', replays the request against the real service and compares the response. An arrow goes from the broker to the provider, and a mark reads verified.

The provider renames name to fullName. Verification fails in the provider build, before any deployment, and names the consumer it would break. The response field reads fullName, and a mark reads that verification fails.

With the field restored, can-i-deploy asks the broker whether this version passed against what runs in production. No end-to-end environment was needed. A mark reads safe to deploy.

The Order service, the consumer, is on the left, with a Pact mock server below it. The Customer service, the provider, is on the right, with a Pact Broker below it. The contract sits across the bottom: the request and the response fields.

The Order service test states what it needs: GET /customers/42 returns an id and a name. It runs against a Pact mock server, with no provider running.

The test passes, so Pact writes the contract to a file: the request, and only the response fields this consumer really uses. The contract panel fills in.

The consumer build publishes the contract to a Pact Broker, tagged with its version, where the provider team can find it. An arrow goes from the contract to the broker.

The provider's build fetches the contract, sets up the state 'customer 42 exists', replays the request against the real service and compares the response. An arrow goes from the broker to the provider, and a mark reads verified.

The provider renames name to fullName. Verification fails in the provider build, before any deployment, and names the consumer it would break. The response field reads fullName, and a mark reads that verification fails.

With the field restored, can-i-deploy asks the broker whether this version passed against what runs in production. No end-to-end environment was needed. A mark reads safe to deploy.

Takeaway: A contract test checks both sides of an API separately: the consumer against a mock built from the contract, and the provider against that same contract.

What each kind of test proves between two servicesA consumer test with a hand-written mock proves the consumer works with what you assumed. A contract test proves both sides agree on the API, with neither deployed. An end-to-end test proves the deployed systems work together, at the highest cost.Two services:what to prove?Our ownassumption:a hand-written mockBoth sides agree:a contract testDeployed together:an end-to-end test
What each kind of test proves between two servicesA consumer test with a hand-written mock proves the consumer works with what you assumed. A contract test proves both sides agree on the API, with neither deployed. An end-to-end test proves the deployed systems work together, at the highest cost.Two services:what to prove?Our ownassumption:a hand-written mockBoth sides agree:a contract testDeployed together:an end-to-end test
What each kind of test proves between two services

In code

@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "customer-service")
class CustomerClientPactTest {
    @Pact(consumer = "order-service")
    RequestResponsePact customerExists(PactDslWithProvider builder) {
        return builder
            .given("customer 42 exists")
            .uponReceiving("a request for customer 42")
            .path("/customers/42").method("GET")
            .willRespondWith().status(200)
            .body(new PactDslJsonBody().integerType("id", 42).stringType("name", "Ana"))
            .toPact();
    }

    @Test
    void readsTheCustomer(MockServer server) {
        var client = new CustomerClient(server.getUrl());
        assertEquals("Ana", client.find(42).name());
    }
}
Consumer: state what you need, test against a mock server
@Provider("customer-service")
@PactBroker
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class CustomerProviderPactTest {
    @LocalServerPort int port;
    @Autowired CustomerRepository customers;

    @BeforeEach
    void target(PactVerificationContext context) {
        context.setTarget(new HttpTestTarget("localhost", port));
    }

    @TestTemplate
    @ExtendWith(PactVerificationInvocationContextProvider.class)
    void verifyContracts(PactVerificationContext context) {
        context.verifyInteraction();
    }

    @State("customer 42 exists")
    void customerExists() {
        customers.save(new Customer(42, "Ana"));
    }
}
Provider: replay every contract against the real service
A renamed field stops in the provider's buildThe provider renames name to fullName. Its build fetches the contract and replays the request. The response has no name field, so verification fails, the build stops, and nothing reaches production.Provider renamesnameBuild fetches thecontractReplays GET/customers/42No name field: failsBuild stops beforedeploy
A renamed field stops in the provider's buildThe provider renames name to fullName. Its build fetches the contract and replays the request. The response has no name field, so verification fails, the build stops, and nothing reaches production.Provider renamesnameBuild fetches thecontractReplays GET/customers/42No name field: failsBuild stops beforedeploy
A renamed field stops in the provider's build
request:
  method: GET
  url: /orders/42
response:
  status: 200
  headers:
    Content-Type: application/json
  body:
    id: 42
    status: PAID
Spring Cloud Contract: the agreement written as a provider-side YAML contract

Solve it

Rename a response field without breaking any consumer

The order service wants to rename status to state in GET /orders/{id}. Three consumer teams have Pact contracts in the broker. A direct rename would break whichever consumer deploys last. Plan the rollout.

  1. Find who reads the field. The broker shows which consumer contracts mention status; those consumers must move before the field can go.
  2. Expand. The provider returns both status and state with the same value. Every existing contract still passes.
  3. Migrate. Each consumer switches to state and publishes a new contract that no longer mentions status.
  4. Contract the API. When no deployed consumer version needs status, remove it. Provider verification proves it.
  5. Check each deploy. Run can-i-deploy in every pipeline, so no version reaches production with a broken contract.
record OrderView(long id, String state) {
    @Deprecated
    @JsonProperty("status")
    String status() { return state; }      // removed once no consumer contract mentions "status"
}
Expand: both names until no contract reads the old one
pact-broker can-i-deploy --pacticipant order-service --version "$GIT_SHA" --to-environment production
Gate each deploy on the contracts

How to answer

  • A hand-written mock only tests your own assumption; a contract is checked on both sides.
  • Failures point at one API and one consumer, not a whole environment.
  • Contract tests check the shape of an API, not its business rules.
  • Keep a few end-to-end tests for the critical flows.

Common mistakes

  • Thinking contract tests replace functional tests of the provider's logic.
  • Asserting every field in the contract, which blocks changes no consumer cares about.

Follow-up questions

What is the difference between Pact and Spring Cloud Contract?

They start from opposite sides. In Pact, contracts are consumer-driven: consumer tests generate them, so the provider learns exactly which fields are used, and it works across languages. In Spring Cloud Contract, contracts usually live with the producer, written in Groovy or YAML; it generates tests for the producer and WireMock stubs for consumers. It fits JVM (Java Virtual Machine) teams on Spring.

  • Consumer-driven contracts fit many consumers with different needs.
  • A shared broker or a stubs JAR (Java archive) is how each tool distributes contracts.
  • Spring Cloud Contract can also support a consumer-driven workflow, through pull requests to the producer.

See it in the infographic: The consumer writes it, the provider verifies it

Isn't validating against an OpenAPI schema the same as a contract test?

Not quite. An OpenAPI schema says everything a provider offers, and checking against it shows the response is valid. A consumer-driven contract says what one consumer really uses, so the provider knows which change breaks whom, and can remove a field nobody reads. A schema also rarely covers provider states. Bi-directional approaches compare consumer contracts with the provider's schema.

  • A schema can pass while a consumer still breaks on an assumption it never stated.
  • Contracts show which fields are safe to change.
  • Schemas are still valuable as documentation and for generating clients.

See it in the infographic: The consumer writes it, the provider verifies it

What does can-i-deploy do?

It is a Pact Broker check run before deploying. The broker records which versions of each consumer and provider have passed verification together, and which versions run in each environment. can-i-deploy answers whether this version is compatible with what is deployed there, and fails the pipeline if it is not.

Check yourself

1. A provider renames a response field that a consumer's contract uses. Where does this fail first?
Show answers
  • In the provider's build, during contract verification: Correct. The provider replays the contract and finds the field missing, before anything is deployed.
  • In the consumer's build: Incorrect. The consumer tests against a mock from its own contract, which has not changed.
  • In production, on the first real request: Incorrect. That is the failure contract tests exist to prevent.
2. What does the consumer's Pact test call?
Show answers
  • A mock server built from the contract it declares: Correct. The provider is not running; the mock answers as the contract says.
  • The real provider in a test environment: Incorrect. Needing a running provider is what contract testing avoids.
  • The Pact Broker: Incorrect. The broker stores contracts and results; it does not answer API requests.