Open in TheBrain

3. Provider-Side Testing

Setting up Provider-Side Testing in PACT Testing ensures that the provider complies with the expectations defined in the consumer's contract. Here's how to configure it step by step:


1. Prepare the Provider Project

- Ensure your provider's project is set up and ready for testing (e.g., APIs or services exposed by the provider should be functional).

- Install the relevant Pact provider library for your language:

     - **Java**: Use `pact-jvm-provider` dependency.
     - **JavaScript**: Use the `@pact-foundation/pact` library.
     - **Ruby**: Use the Pact Ruby gem.

2. Fetch the Pact File

- Obtain the PACT file generated by the consumer-side tests. This file contains the contract and defines the expected requests and responses.

- You can:

     - Share the file manually.
     - Use a **Pact Broker** for automatic sharing and versioning.

3. Set Up Verification Tests

- Write tests in the provider project to verify compliance with the contract.

- These tests use the PACT library to:

     - Parse the PACT file.
     - Simulate the requests defined in the contract.
     - Compare the actual provider responses with the expected responses.

Example (JavaScript):

const { Verifier } = require('@pact-foundation/pact');

describe('Provider Verification', () => {

     it('should verify the provider against the consumer contract', async () => {
       const opts = {
         providerBaseUrl: 'http://localhost:8080', // Provider's base URL
         pactUrls: ['./pacts/ConsumerService-ProviderService.json'], // Path to the Pact file
       };
       await new Verifier(opts).verifyProvider().then(() => {
         console.log('Provider verified successfully!');
       });
     });

});

```


4. Configure the Provider

- Ensure the provider starts in the expected state before running tests.

- You can use provider states to simulate specific scenarios. For example:

     - A database with pre-seeded data.
     - Mocked dependencies or services.

- Define state handlers in the provider tests to match the states specified in the PACT file.


5. Automate Verification

- Integrate the provider verification tests into your CI/CD pipeline.

- Regularly verify the provider's implementation against all consumer contracts, especially after making changes to the provider.


6. Publish Verification Results

- Use a Pact Broker to publish the results of the provider verification.

- This step enables visibility for both consumer and provider teams, ensuring compatibility.


7. Resolve Issues Promptly

- If any verification tests fail, address the issues promptly in collaboration with the consumer team.

- Update the contract and provider implementation as needed.