contracts: consumer-driven contract testing lab (Spring Cloud Contract 5.0.3, Stubborn Contract 0.2.4, Pact JVM 4.7.7 on Spring Boot 4.2.0)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b7h4ZNF4BDUpJk3Zou
This commit is contained in:
Claude
2026-11-29 02:29:20 +05:30
parent d7497c8ab1
commit 8a429ca578
46 changed files with 1986 additions and 0 deletions
@@ -0,0 +1,9 @@
package com.ankurm.contracts.orders;
import java.math.BigDecimal;
import java.util.List;
/** The producer's own domain object. What goes on the wire is decided by {@link OrderRepresentation}. */
public record Order(long id, String status, BigDecimal total, String currency, List<Line> items) {
public record Line(String sku, int qty) {}
}
@@ -0,0 +1,39 @@
package com.ankurm.contracts.orders;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OrderController {
public record CreateOrder(List<Order.Line> items) {}
private final OrderRepository repository;
private final String variant;
OrderController(OrderRepository repository, @Value("${orders.variant:baseline}") String variant) {
this.repository = repository;
this.variant = variant;
}
@GetMapping("/orders/{id}")
ResponseEntity<Map<String, Object>> get(@PathVariable long id) {
return repository.find(id)
.map(o -> ResponseEntity.ok(OrderRepresentation.of(o, variant)))
.orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "ORDER_NOT_FOUND")));
}
@PostMapping("/orders")
ResponseEntity<Map<String, Object>> create(@RequestBody CreateOrder request) {
Order order = repository.create(request.items());
return ResponseEntity.status(HttpStatus.CREATED).body(OrderRepresentation.of(order, variant));
}
}
@@ -0,0 +1,43 @@
package com.ankurm.contracts.orders;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Repository;
@Repository
public class OrderRepository {
public static final long FIRST_NEW_ID = 1001;
private static final Map<String, BigDecimal> PRICES = Map.of("BOOK-1", new BigDecimal("64.95"), "PEN-7", new BigDecimal("5.00"));
private final Map<Long, Order> orders = new ConcurrentHashMap<>();
private final AtomicLong sequence = new AtomicLong(FIRST_NEW_ID);
public Optional<Order> find(long id) {
return Optional.ofNullable(orders.get(id));
}
public Order create(List<Order.Line> lines) {
BigDecimal total = lines.stream()
.map(l -> PRICES.getOrDefault(l.sku(), BigDecimal.ZERO).multiply(BigDecimal.valueOf(l.qty())))
.reduce(BigDecimal.ZERO, BigDecimal::add);
Order order = new Order(sequence.getAndIncrement(), "NEW", total, "INR", lines);
orders.put(order.id(), order);
return order;
}
public void save(Order order) {
orders.put(order.id(), order);
}
/** Test support: back to a known state so every contract starts from the same data. */
public void reset() {
orders.clear();
sequence.set(FIRST_NEW_ID);
save(new Order(42, "CONFIRMED", new BigDecimal("129.90"), "INR", List.of(new Order.Line("BOOK-1", 2))));
}
}
@@ -0,0 +1,40 @@
package com.ankurm.contracts.orders;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Builds the JSON the API returns. The {@code orders.variant} property exists only so this lab can
* simulate a producer change on demand; a real service would just have the change in its code.
*
* <ul>
* <li>{@code baseline} - id, status, total, currency, items</li>
* <li>{@code add-field} - baseline plus a new field "discount" (additive, backwards compatible)</li>
* <li>{@code rename-total} - "total" renamed to "totalAmount" (breaking for everyone who reads total)</li>
* <li>{@code drop-items} - "items" removed (breaking only for someone who reads items)</li>
* <li>{@code total-string} - "total" serialised as a string "129.90" instead of a number</li>
* </ul>
*/
public final class OrderRepresentation {
private OrderRepresentation() {}
public static Map<String, Object> of(Order o, String variant) {
Map<String, Object> json = new LinkedHashMap<>();
json.put("id", o.id());
json.put("status", o.status());
switch (variant) {
case "rename-total" -> json.put("totalAmount", o.total());
case "total-string" -> json.put("total", o.total().toPlainString());
default -> json.put("total", o.total());
}
json.put("currency", o.currency());
if (!variant.equals("drop-items")) {
json.put("items", o.items());
}
if (variant.equals("add-field")) {
json.put("discount", 0);
}
return json;
}
}
@@ -0,0 +1,11 @@
package com.ankurm.contracts.orders;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class OrdersApplication {
public static void main(String[] args) {
SpringApplication.run(OrdersApplication.class, args);
}
}
@@ -0,0 +1 @@
spring.application.name=orders-producer
@@ -0,0 +1,29 @@
package com.ankurm.contracts.orders;
import io.restassured.RestAssured;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
/**
* Base class for the tests that Spring Cloud Contract generates from src/test/resources/contracts.
* Each generated test extends this class, so it is where the producer puts itself into the state
* the contract describes (order 42 exists, the next new id is 1001).
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class ContractVerifierBase {
@LocalServerPort
int port;
@Autowired
OrderRepository repository;
@BeforeEach
void setUp() {
RestAssured.baseURI = "http://localhost";
RestAssured.port = port;
repository.reset();
}
}
@@ -0,0 +1,60 @@
package com.ankurm.contracts.orders;
import au.com.dius.pact.provider.junit5.HttpTestTarget;
import au.com.dius.pact.provider.junit5.PactVerificationContext;
import au.com.dius.pact.provider.junit5.PactVerificationInvocationContextProvider;
import au.com.dius.pact.provider.junitsupport.Provider;
import au.com.dius.pact.provider.junitsupport.State;
import au.com.dius.pact.provider.junitsupport.loader.PactFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import java.math.BigDecimal;
import java.util.List;
/**
* Pact provider verification: replays every interaction recorded in the consumer's pact file
* against this running service and compares the real response with what the consumer said it needs.
* The pact file is the consumer's artefact; the producer team never writes it.
*/
@Provider("orders-producer")
@PactFolder("pacts")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(PactVerificationInvocationContextProvider.class)
class OrdersPactVerificationTest {
@LocalServerPort
int port;
@Autowired
OrderRepository repository;
@BeforeEach
void before(PactVerificationContext context) {
context.setTarget(new HttpTestTarget("localhost", port));
}
@TestTemplate
void verifyPact(PactVerificationContext context) {
context.verifyInteraction();
}
@State("order 42 exists and is confirmed")
void order42Exists() {
repository.reset();
}
@State("order 999 does not exist")
void order999Missing() {
repository.reset();
}
@State("orders can be created")
void canCreate() {
repository.reset();
}
}
@@ -0,0 +1,23 @@
description: posting order lines creates a NEW order with a computed total
name: shouldCreateOrder
request:
method: POST
url: /orders
headers:
Content-Type: application/json
body:
items:
- sku: "BOOK-1"
qty: 2
response:
status: 201
headers:
Content-Type: application/json
body:
id: 1001
status: "NEW"
total: 129.90
currency: "INR"
items:
- sku: "BOOK-1"
qty: 2
@@ -0,0 +1,11 @@
description: an unknown order id gives 404 with an error code
name: shouldReturn404ForUnknownOrder
request:
method: GET
url: /orders/999
response:
status: 404
headers:
Content-Type: application/json
body:
error: "ORDER_NOT_FOUND"
@@ -0,0 +1,17 @@
description: a confirmed order is returned by id
name: shouldReturnOrder
request:
method: GET
url: /orders/42
response:
status: 200
headers:
Content-Type: application/json
body:
id: 42
status: "CONFIRMED"
total: 129.90
currency: "INR"
items:
- sku: "BOOK-1"
qty: 2
@@ -0,0 +1,166 @@
{
"consumer": {
"name": "checkout-consumer"
},
"interactions": [
{
"description": "a request for order 42",
"providerStates": [
{
"name": "order 42 exists and is confirmed"
}
],
"request": {
"method": "GET",
"path": "/orders/42"
},
"response": {
"body": {
"id": 42,
"status": "CONFIRMED",
"total": 129.9
},
"headers": {
"Content-Type": "application/json"
},
"matchingRules": {
"body": {
"$.id": {
"combine": "AND",
"matchers": [
{
"match": "integer"
}
]
},
"$.status": {
"combine": "AND",
"matchers": [
{
"match": "type"
}
]
},
"$.total": {
"combine": "AND",
"matchers": [
{
"match": "decimal"
}
]
}
}
},
"status": 200
}
},
{
"description": "a request for an unknown order",
"providerStates": [
{
"name": "order 999 does not exist"
}
],
"request": {
"method": "GET",
"path": "/orders/999"
},
"response": {
"status": 404
}
},
{
"description": "a request to create an order",
"providerStates": [
{
"name": "orders can be created"
}
],
"request": {
"body": {
"items": [
{
"qty": 2,
"sku": "BOOK-1"
}
]
},
"headers": {
"Content-Type": "application/json"
},
"matchingRules": {
"body": {
"$.items[0].qty": {
"combine": "AND",
"matchers": [
{
"match": "integer"
}
]
},
"$.items[0].sku": {
"combine": "AND",
"matchers": [
{
"match": "type"
}
]
}
}
},
"method": "POST",
"path": "/orders"
},
"response": {
"body": {
"id": 1001,
"status": "NEW",
"total": 129.9
},
"headers": {
"Content-Type": "application/json"
},
"matchingRules": {
"body": {
"$.id": {
"combine": "AND",
"matchers": [
{
"match": "integer"
}
]
},
"$.status": {
"combine": "AND",
"matchers": [
{
"match": "type"
}
]
},
"$.total": {
"combine": "AND",
"matchers": [
{
"match": "decimal"
}
]
}
}
},
"status": 201
}
}
],
"metadata": {
"pact-jvm": {
"version": "4.7.7"
},
"pactSpecification": {
"version": "3.0.0"
}
},
"provider": {
"name": "orders-producer"
}
}