QA AND TEST AUTOMATION · PART 4 · API TESTING · TECHNIQUE · 45 OF 112

Contract Testing with Pact: Consumer-Driven Contracts

Consumer-driven contract testing with Pact, run for real: ShopRung's web page is the consumer and its API the provider. The consumer test writes a pact file against a Pact mock, the provider verifies it against the real API, and a missing field fails with an exact diff. Matchers, provider states, the Java (Pact JVM) version, the Pact Broker and can-i-deploy.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Consumer test → pact file → provider verification
  • matchers
  • provider states
  • broker and can-i-deploy

Notes

The roles

Two roles. The consumer is the code that calls an API: a web app, a mobile app or another service. The provider is the API that answers. ShopRung has both: its web page's JavaScript is a consumer of the ShopRung API. A contract is the list of requests the consumer makes, and the parts of each response it actually relies on. Not the whole response; only what the consumer uses.

Who is who
  • consumer: code that CALLS an API (web app, mobile app, another service)
  • provider: the API answering
  • ShopRung: the web page's app.js is a consumer of the ShopRung API
  • contract = the requests the consumer makes + the parts of responses it relies on

Step 1: consumer test

Step one runs on the consumer side. The test describes an interaction: given product one exists, upon receiving a get for product one, respond two hundred with an id, a sku and a price in cents. Pact starts a mock server that answers exactly that. The consumer's real code calls the mock, and the test checks it handles the answer. If the test passes, Pact writes the interaction to a pact file. Ours passed and wrote shoprung web, shoprung api dot json.

pact-python (v3 API)
pact = Pact("shoprung-web",
            "shoprung-api")
(pact.upon_receiving("product 1")
  .given("product 1 exists")
  .with_request("GET", "/api/products/1")
  .will_respond_with(200)
  .with_body({"id": match.int(1),
    "sku": match.regex("BK-101", ...),
    "priceCents": match.int(1250)}))
with pact.serve() as srv:
    assert get_price(srv.url, 1) == ...

Matchers

Matchers keep contracts from being brittle. Match int twelve fifty means any integer, with twelve fifty as the example the mock returns. Match regex says the sku must look like two letters, a dash and three digits. Each like describes an array whose items all look like an example. The pact file stores the examples and these matching rules, so the provider can return any real product and still pass, as long as the shape is right.

Flexible rules
match.int(1250)
  any integer (1250 = example)
match.regex("BK-101",
  regex=r"^[A-Z]{2}-\d{3}$")
match.str("Clean Code ...")
match.each_like({...})
  array of items like this

pact file stores examples
  + "matchingRules"

Step 2: verify provider

Step two runs on the provider side, with no consumer code at all. The verifier reads the pact file, replays each request against the real provider, and checks each response against the rules. We verified our pact against the real ShopRung API: status two hundred, OK; content type header, OK; matching body, OK. Extra fields the consumer does not use, like name and stock, are fine, because the consumer does not rely on them.

Real verification output
Verifier("shoprung-api")
  .add_transport(url=BASE)
  .add_source("pacts/").verify()

a request for product 1
  Given product 1 exists
  has status code 200 (OK)
  includes headers
    "Content-Type" (OK)
  has a matching body (OK)

A broken contract

Then we broke it on purpose. A new consumer version expected an image URL field for product pictures, which the ShopRung API does not send. The consumer test still passed, because the mock returns whatever the contract says. But provider verification failed: the actual map is missing the following keys, image URL, with a diff. That is the bug caught before deployment, without starting a browser or the whole system.

Real failure
has a matching body (FAILED)

1.1) has a matching body
  $ -> Actual map is missing
       the following keys:
       imageUrl
  - "imageUrl": "x.png",
  + "category": "Books",
  + "inStock": true,

Provider states

Interactions can name a provider state, like product one exists, or Alice has an order. Before replaying that interaction, the provider's verification calls a state handler that sets up the data, for example through a test endpoint or the database. For ShopRung, a reset makes product one exist. Without provider states, verification depends on whatever data happens to be there, which makes it flaky.

Provider states
  • each interaction can say given("product 1 exists") given("alice has an order")
  • the provider registers a handler per state that creates or resets the data
  • ShopRung: POST /api/test/reset makes "product 1 exists" true

In Java

Java teams use Pact JVM with JUnit five, and the steps are the same. The consumer test is annotated with the Pact consumer extension, and a Pact method builds the interaction with a builder: given, upon receiving, will respond with. The provider test names the provider, says where the pact files are, and has a method per provider state, annotated with State. A test template verifies every interaction.

Pact JVM (outline)
// consumer
@ExtendWith(PactConsumerTestExt.class)
@Pact(consumer = "shoprung-web")
V4Pact product(PactDslWithProvider b)
  { return b.given("product 1 exists")
    .uponReceiving(...)...toPact(); }
// provider
@Provider("shoprung-api")
@PactFolder("pacts")
@State("product 1 exists")
void reset() { ... }

In CI

In real teams, consumer and provider live in different repositories. A Pact Broker, self hosted or as a hosted service, shares the contracts. Consumer CI runs its tests and publishes the pact. Provider CI fetches every pact that names it, verifies, and publishes the results. Before either side deploys, the can I deploy command asks the broker whether that version is compatible with what is already in the target environment.

Pact Broker workflow
  • consumer CI: test, then publish pact to the broker
  • provider CI: fetch all pacts for it, verify, publish the results
  • before deploying either side: pact-broker can-i-deploy → yes only if versions in that environment agree

Common mistakes

Mistakes to avoid. Exact values instead of matchers, which breaks on every data change. Contracts that list fields the consumer never uses, which blocks the provider for no reason. Using Pact to test business logic, like discount rules; that belongs in functional API tests. No provider states. Publishing contracts but never running can I deploy. And adopting it on one side only: contract testing needs both teams.

Avoid these
  • exact values instead of matchers (brittle)
  • contracts listing fields the consumer never uses
  • using Pact to test provider business logic
  • no provider states
  • never running can-i-deploy
  • one team only: no consumer

Say it like this

In the interview: contract testing checks that a consumer and a provider agree, with each tested separately. In consumer driven contracts, the consumer's test runs against a Pact mock and records the requests and the response fields it relies on, using matchers. The provider replays them against its real API, with provider states for data. A broker shares pacts, and can I deploy blocks incompatible releases. It replaces many slow end to end tests, not functional tests.

In the interview
  • "Consumer-driven contracts: the consumer test runs against
  • a Pact mock and records the requests and the response
  • fields it relies on. The provider replays them against
  • its real API with provider
  • states. A broker shares pacts
  • and can-i-deploy blocks
  • incompatible releases."

Interview questions

Q1What is contract testing?

Testing that a consumer and a provider agree on their interface (requests and the response parts the consumer uses), with each side tested in isolation.

Q2What is consumer-driven contract testing?

The consumer defines the contract through its tests (against a mock), and the provider verifies it can satisfy every consumer's contract.

Q3What is a pact file?

A JSON contract generated by the consumer test, listing interactions with example requests and responses plus matching rules.

Q4What are provider states?

Named preconditions (for example "product 1 exists") that the provider sets up through handlers before replaying an interaction.

Q5Why use matchers in Pact?

So the contract checks types and patterns instead of exact values, letting the provider return real data without breaking verification.

Q6What is can-i-deploy?

A Pact Broker command that checks whether a version of a consumer or provider is verified as compatible with the versions in the target environment.

Q7How is contract testing different from schema validation?

A schema describes everything the provider may return; a contract records what each consumer actually uses and is verified against the provider in CI for every consumer.

Q8Does contract testing replace end-to-end tests?

It replaces many integration and end-to-end checks of service interfaces, but not functional tests of business logic or a small set of critical end-to-end journeys.