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’)

            }

        }

}
 
The API that we want to call is http://test.api.com.au:80/consumer/search. Consumer-Provider.json is the PACT file generated by the Consumer test in my previous Consumer test blog. The file name “Consumer-Provider.json” is based on the “serviceConsumer” and “hasPactWith” definitions in the Consumer test. “APITests” is the root directory of the project, while “target” is the default directory where PACT files are going to be generated. However, this maybe overwritten (refer to the original GitHub wiki on how to do this). “hasPactWith(‘Consumer’)” in Provider test is merely a name. This is useful so we can run each test individually.
You may define as many tests as you want inside the “pact” segment.

    @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.