How to Contract Test With Spring Cloud Contract
Spring Cloud Contract is producer-driven: the producer defines contracts, the plugin generates verification tests, and consumers pull the resulting stubs.
Write contracts under src/test/resources/contracts. The Maven or Gradle plugin generates base-class-driven tests for the producer and publishes a stub jar consumers use with Stub Runner.
Steps
- Add the
spring-cloud-contractplugin to the producer build. - Write contracts in Groovy DSL or YAML under the contracts directory.
- Run the build in CI to generate tests and publish the stub jar.
CI build
.github/workflows/ci.yml
jobs:
contracts:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: 21
- run: ./mvnw -B test
- run: ./mvnw -B deploy -DskipTestsGotchas
- Spring Cloud Contract is producer-driven, the inverse of Pact consumer-driven flow; pick one direction per integration.
- The generated tests need a configured base class that stands up the controller context.
Related guides
What Contract Testing Is and When to Use ItConsumer-driven contract testing verifies that a consumer and provider agree on an API by exchanging a contra…
Contract Testing vs End-to-End Tests: Honest Trade-offsCompare contract testing and end-to-end tests honestly: contract tests are fast and isolate the API agreement…