Consumer Driven Contract Testing using Pact
Code sample using Pact with Android frontend and Spring Boot backend.
This sample uses Packflow to share and view Pact contracts. View an example pact here.
To fully try out this sample, create an account on Packflow and replace the PACT_BROKER_BASE_URL
and PACT_BROKER_TOKEN
below with your own.
-
Open the To Do Android project in Android Studio
-
Gradle build task will generate a pact file in app/build/pacts folder based on existing contract tests AddToDoContractTest.kt and GetToDosContractTest.kt.
cd todo-android
./gradlew clean build
- Gradle pactPublish task will publish the pact file into a pact broker. Be sure to specify the following environment variables used in app/build.gradle
Environment variables needed for To Do Android. Add these when running pactPublish
gradle task.
PACT_BROKER_BASE_URL=https://djoo.pactflow.io
PACT_BROKER_TOKEN=[pactflow-read/write-token]
These env vars are read in the pact.publish section in the app/build.gradle
pact {
publish {
pactBrokerUrl = System.getenv('PACT_BROKER_BASE_URL')
pactBrokerToken = System.getenv('PACT_BROKER_TOKEN')
}
}
To publish the latest pact file to a pact broker: (Pactflow in this example)
cd todo-android
./gradlew pactPublish
- Contract tests in To Do Server project validates the API to the published pact file. Be sure to specify the following environment variable needed to run the PactVerificationTest.java
Environment variables needed for To Do Server. Note the base url has removed the method "https://" portion. Add these when running PactVerificationTest.java
PACT_BROKER_BASE_URL=djoo.pactflow.io
PACT_BROKER_TOKEN=[pactflow-read/write-token]
Flag pact.verifier.publishResults=true
specified in todo-server/build.gradle test block publishes verification results to Pactflow after running tests.
To verify, simply run the PactVerificationTest.java
cd todo-server
PACT_BROKER_BASE_URL=[pactflow-url] PACTBROKER_AUTH_TOKEN=[pactflow-read/write-token] ./gradlew test --tests "*PactVerificationTest*"
- Sign on to Packflow and confirm a pact is present and verified.