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,11 @@
package com.ankurm.contracts.checkout;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CheckoutApplication {
public static void main(String[] args) {
SpringApplication.run(CheckoutApplication.class, args);
}
}
@@ -0,0 +1,24 @@
package com.ankurm.contracts.checkout;
import java.math.BigDecimal;
import org.springframework.stereotype.Service;
@Service
public class CheckoutService {
private final OrderClient orders;
public CheckoutService(OrderClient orders) {
this.orders = orders;
}
/** What the customer owes for a confirmed order. Anything else is not payable. */
public BigDecimal amountDue(long orderId) {
Order order = orders.find(orderId)
.orElseThrow(() -> new IllegalArgumentException("no such order " + orderId));
if (!"CONFIRMED".equals(order.status())) {
throw new IllegalStateException("order " + orderId + " is " + order.status());
}
return order.total();
}
}
@@ -0,0 +1,10 @@
package com.ankurm.contracts.checkout;
import java.math.BigDecimal;
/**
* The consumer's view of an order: only the three fields checkout actually uses.
* The producer also sends currency and items; this service never reads them, so a Pact contract
* written from this class does not mention them either.
*/
public record Order(long id, String status, BigDecimal total) {}
@@ -0,0 +1,44 @@
package com.ankurm.contracts.checkout;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
@Component
public class OrderClient {
public record Line(String sku, int qty) {}
private record CreateOrder(List<Line> items) {}
private final RestClient http;
public OrderClient(RestClient.Builder builder, @Value("${orders.base-url}") String baseUrl) {
this.http = builder.baseUrl(baseUrl).build();
}
public Optional<Order> find(long id) {
return http.get().uri("/orders/{id}", id)
.exchange((request, response) -> {
if (response.getStatusCode() == HttpStatus.NOT_FOUND) {
return Optional.<Order>empty();
}
if (response.getStatusCode().isError()) {
throw new IllegalStateException("orders-producer answered " + response.getStatusCode());
}
return Optional.of(response.bodyTo(Order.class));
});
}
public Order create(List<Line> lines) {
return http.post().uri("/orders")
.contentType(MediaType.APPLICATION_JSON)
.body(new CreateOrder(lines))
.retrieve()
.body(Order.class);
}
}
@@ -0,0 +1 @@
orders.base-url=http://localhost:8080
@@ -0,0 +1,49 @@
package com.ankurm.contracts.checkout;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.math.BigDecimal;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import sh.stubborn.contract.stubrunner.spring.AutoConfigureStubRunner;
import sh.stubborn.contract.stubrunner.StubsMode;
/**
* Consumer side of a Spring Cloud Contract. The stubs come from the producer's build, not from this
* project: the stub runner finds orders-producer-1.0.0-stubs.jar in ~/.m2, starts WireMock on port 8090
* and serves exactly the requests and responses the producer's contracts describe.
*/
@SpringBootTest(properties = "orders.base-url=http://localhost:8090")
@AutoConfigureStubRunner(
ids = "com.ankurm.contracts:orders-producer-stubborn:+:stubs:8090",
stubsMode = StubsMode.LOCAL)
class OrdersStubbornConsumerTest {
@Autowired
CheckoutService checkout;
@Autowired
OrderClient client;
@Test
void amountDueComesFromTheStubbedOrder() {
assertThat(checkout.amountDue(42)).isEqualByComparingTo(new BigDecimal("129.90"));
}
@Test
void unknownOrderIsNotPayable() {
assertThatThrownBy(() -> checkout.amountDue(999))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("no such order 999");
}
@Test
void createReturnsTheNewOrder() {
Order order = client.create(List.of(new OrderClient.Line("BOOK-1", 2)));
assertThat(order.id()).isEqualTo(1001);
assertThat(order.status()).isEqualTo("NEW");
}
}
@@ -0,0 +1,110 @@
package com.ankurm.contracts.checkout;
import static org.assertj.core.api.Assertions.assertThat;
import au.com.dius.pact.consumer.MockServer;
import au.com.dius.pact.consumer.dsl.LambdaDsl;
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.consumer.junit5.PactConsumerTestExt;
import au.com.dius.pact.consumer.junit5.PactTestFor;
import au.com.dius.pact.core.model.PactSpecVersion;
import au.com.dius.pact.core.model.RequestResponsePact;
import au.com.dius.pact.core.model.annotations.Pact;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.web.client.RestClient;
/**
* Consumer side of a Pact contract. Running this class does two things: it checks that OrderClient
* works against a mock server shaped like the contract, and it writes target/pacts/*.json, the file
* the producer will later verify itself against.
*
* Only the fields checkout reads (id, status, total) appear in the contract, and they are matched by
* type, not by value. That is the consumer-driven part: the producer stays free to change anything else.
*/
@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "orders-producer", pactVersion = PactSpecVersion.V3)
class OrdersPactConsumerTest {
private static final Map<String, String> JSON = Map.of("Content-Type", "application/json");
@Pact(consumer = "checkout-consumer")
RequestResponsePact orderExists(PactDslWithProvider builder) {
return builder
.given("order 42 exists and is confirmed")
.uponReceiving("a request for order 42")
.path("/orders/42")
.method("GET")
.willRespondWith()
.status(200)
.headers(JSON)
.body(LambdaDsl.newJsonBody(o -> o
.integerType("id", 42)
.stringType("status", "CONFIRMED")
.decimalType("total", 129.90)).build())
.toPact();
}
@Pact(consumer = "checkout-consumer")
RequestResponsePact orderMissing(PactDslWithProvider builder) {
return builder
.given("order 999 does not exist")
.uponReceiving("a request for an unknown order")
.path("/orders/999")
.method("GET")
.willRespondWith()
.status(404)
.toPact();
}
@Pact(consumer = "checkout-consumer")
RequestResponsePact orderCreated(PactDslWithProvider builder) {
return builder
.given("orders can be created")
.uponReceiving("a request to create an order")
.path("/orders")
.method("POST")
.headers(JSON)
.body(LambdaDsl.newJsonBody(o -> o
.array("items", a -> a.object(l -> l.stringType("sku", "BOOK-1").integerType("qty", 2)))).build())
.willRespondWith()
.status(201)
.headers(JSON)
.body(LambdaDsl.newJsonBody(o -> o
.integerType("id", 1001)
.stringType("status", "NEW")
.decimalType("total", 129.90)).build())
.toPact();
}
@Test
@PactTestFor(pactMethod = "orderExists")
void readsAnExistingOrder(MockServer server) {
OrderClient client = new OrderClient(RestClient.builder(), server.getUrl());
Order order = client.find(42).orElseThrow();
assertThat(order.status()).isEqualTo("CONFIRMED");
assertThat(order.total()).isEqualByComparingTo(new BigDecimal("129.90"));
}
@Test
@PactTestFor(pactMethod = "orderMissing")
void anUnknownOrderIsEmpty(MockServer server) {
OrderClient client = new OrderClient(RestClient.builder(), server.getUrl());
assertThat(client.find(999)).isEmpty();
}
@Test
@PactTestFor(pactMethod = "orderCreated")
void createsAnOrder(MockServer server) {
OrderClient client = new OrderClient(RestClient.builder(), server.getUrl());
Order order = client.create(List.of(new OrderClient.Line("BOOK-1", 2)));
assertThat(order.id()).isEqualTo(1001);
assertThat(order.status()).isEqualTo("NEW");
}
}
@@ -0,0 +1,49 @@
package com.ankurm.contracts.checkout;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.math.BigDecimal;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.contract.stubrunner.spring.AutoConfigureStubRunner;
import org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties;
/**
* Consumer side of a Spring Cloud Contract. The stubs come from the producer's build, not from this
* project: the stub runner finds orders-producer-1.0.0-stubs.jar in ~/.m2, starts WireMock on port 8090
* and serves exactly the requests and responses the producer's contracts describe.
*/
@SpringBootTest(properties = "orders.base-url=http://localhost:8090")
@AutoConfigureStubRunner(
ids = "com.ankurm.contracts:orders-producer:+:stubs:8090",
stubsMode = StubRunnerProperties.StubsMode.LOCAL)
class OrdersStubConsumerTest {
@Autowired
CheckoutService checkout;
@Autowired
OrderClient client;
@Test
void amountDueComesFromTheStubbedOrder() {
assertThat(checkout.amountDue(42)).isEqualByComparingTo(new BigDecimal("129.90"));
}
@Test
void unknownOrderIsNotPayable() {
assertThatThrownBy(() -> checkout.amountDue(999))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("no such order 999");
}
@Test
void createReturnsTheNewOrder() {
Order order = client.create(List.of(new OrderClient.Line("BOOK-1", 2)));
assertThat(order.id()).isEqualTo(1001);
assertThat(order.status()).isEqualTo("NEW");
}
}