What is Contract Testing?
Contract testing verifies that an API provider honors the agreements made with its consumers. Instead of running full integration tests, you define the expected interactions and verify them independently.Step 1: Define Contracts
Create acontracts/ directory and define expected interactions:
Step 2: Create a State Handler (Optional)
If your contracts specify@contract.state, create a script that sets up those states:
chmod +x setup-states.sh
Step 3: Verify Contracts
Step 4: CI/CD Integration
Run contract verification as part of the provider’s CI pipeline:Best Practices
- Keep contracts minimal — only assert on fields your consumer actually uses
- Use a dedicated directory — separate contracts from integration tests
- Version your contracts — treat them as API documentation
- Run on both sides — consumers generate contracts, providers verify them
- Use state handlers — ensure reproducible provider states for each interaction