Clean β’ Professional
Contract Testing ensures that two or more services (or systems) communicate correctly by validating that they adhere to a shared βcontractβ (API agreement).
In Spring Boot applications, contract testing validates that request/response formats, endpoints, and data structures remain consistent across services, helping prevent runtime integration failures.
A contract defines the expectations between a consumer (service calling an API) and a provider (service providing the API):
/api/users/1)
Contracts ensure that both sides agree on the format and behavior of API communication.
| Tool | Purpose |
|---|---|
| Pact | Consumer-driven contract testing for REST and messaging APIs |
| Spring Cloud Contract | Producer-driven contract tests integrated with Spring Boot |
| Postman / Newman | Manual contract validation using API collections |
1. Contract Definition (src/test/resources/contracts/user.groovy)
Contract.make {
request {
method 'GET'
url '/api/users/1'
}
response {
status 200
body(
id: 1,
name: "Alice",
email: "[email protected]"
)
headers {
contentType(applicationJson())
}
}
}
2. Provider Test (Spring Boot)
@SpringBootTest
@AutoConfigureMockMvc
classUserControllerContractTest {
// Generated tests verify the API satisfies the contract
}
3. Consumer Verification Test
@SpringBootTest
@AutoConfigureStubRunner(ids = "com.example:users-service:+:stubs:8080", workOffline = true)
classUserServiceConsumerTest {
@Autowired
private UserService userService;
@Test
voidshouldFetchUserById() {
Useruser= userService.getUserById(1);
assertEquals("Alice", user.getName());
}
}
Pact is a consumer-driven contract testing tool that ensures microservices agree on API contracts before production.
How Pact Works
@Pact(consumer = "user-consumer", provider = "user-provider")
public RequestResponsePactcreatePact(PactDslWithProvider builder) {
return builder
.given("User with ID 1 exists")
.uponReceiving("A request for user details")
.path("/api/users/1")
.method("GET")
.willRespondWith()
.status(200)
.body("{\\"id\\":1,\\"name\\":\\"Alice\\",\\"email\\":\\"[email protected]\\"}")
.toPact();
}
@RunWith(SpringRestPactRunner.class)
@Provider("user-provider")
@PactFolder("pacts")// Folder containing consumer contracts
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
publicclassUserProviderPactTest {
}
| Feature | Description |
|---|---|
| Prevents Integration Failures | Ensures consumer and producer agree on API contracts |
| Early Issue Detection | Detects breaking changes before production |
| Independent Evolution | Microservices can change independently without breaking integrations |
| CI/CD Support | Enables automated contract verification in pipelines |
| Reduced Manual Testing | Contracts and stubs reduce repetitive integration tests |
Contract Testing in Spring Boot guarantees that your microservices remain robust, integration-safe, and reliable while allowing independent evolution of services.