Answer
Contract Testing
Contract testing is a technique for testing an integration point by checking each application in isolation to ensure the messages it sends or receives conform to a shared understanding documented in a contract.
When to Use Contract Testing
Contract testing is immediately applicable anywhere where you have two services that need to communicate — such as an API client and a web front-end.
It really shines in an environment with many services (as is common in a microservice architecture). Having well-formed contract tests makes it easy for developers to avoid version hell.
Consumer-Driven Contract Testing
In microservices, the consumer (client) defines what it expects from the provider (API server). The contract is tested independently on both sides.
Consumer (Frontend) ──→ defines expected API shape ──→ Contract
Provider (API Server) ──→ verifies it fulfils the contract ──→ Pass/Fail
Popular Tools
| Tool | Language | Description |
|---|---|---|
| Pact | Java, JS, Ruby, .NET | Most popular consumer-driven contract testing |
| Spring Cloud Contract | Java/Spring | Contract testing for Spring microservices |
| Dredd | Any | API Blueprint/OpenAPI contract testing |
Example with Pact (Java)
@ExtendWith(PactConsumerTestExt.class)
public class UserServiceConsumerTest {
@Pact(consumer = "FrontendApp", provider = "UserAPI")
public RequestResponsePact createPact(PactDslWithProvider builder) {
return builder
.given("user 1 exists")
.uponReceiving("get user by id")
.path("/api/users/1")
.method("GET")
.willRespondWith()
.status(200)
.body(new PactDslJsonBody()
.integerType("id", 1)
.stringType("name", "John"))
.toPact();
}
}
Contract Testing vs Integration Testing
| Feature | Contract Testing | Integration Testing |
|---|---|---|
| Isolation | Tests each service independently | Tests services together |
| Speed | Fast | Slower |
| Feedback | Early detection | Late detection |
| Environment | No live environment needed | Needs running services |
Contract testing is a killer app for microservice development and deployment.
