Writing PACT provider test is easy because you do not need to write them, you only need to call them!
Example below is in Groovy using the Gradle framework.
(1) Import the library and include it in the build script
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath ‘au.com.dius:pact-jvm-provider-gradle_2.11:3.0.1’
}
}
(2) In build.gradle, call the API, which is the Provider and define the location of the PACT JSON file generated by the Consumer test. These are done under a “pact” segment.
pact {
dataProviders {
DataProvider {
protocol = ‘http’
host = ‘test.api.com.au’
port = 80
path = ‘/consumer/search’
hasPactWith(‘Consumer’) {
pactFile = file(‘..\ApiTests\target\pacts\Consumer-Provider.json’)
}
}
@Test
void “Consumer test for Consumer and Provider”() {
def consumer_service = new PactBuilder()
consumer_service {
serviceConsumer “Consumer”
hasPactWith “Provider”
(3) Execute the command gradle pactVerify from the root directory of the project. Or to call the test individually, we may specify gradle pactVerify -Ppact.filter.consumer=[hasPactWith value]Example of output:
PACT Provider will call the API that you defined in gradle.build and compare the actual output against the output generated by Consumer test. It compares for the response status, content type, and body as how you defined them.
This way, we know that the API contract that the Consumer expects is similar as what the API Provider produces.
Example of a PACT Provider failure:
In the example above, value Type is returned as “Car” but it is defined as an integer in the Consumer test.
Leave a Reply