Contract testing is a technique used to ensure that different systems or services that interact with each other do so in the way that they are expected to. In the context of APIs, contract testing is used to ensure that an API adheres to its specified contract, which includes the expected inputs, outputs, and error conditions.

One example of contract testing in API development is the use of a tool like Pact, which allows API consumers and providers to agree on the contract of the API before any implementation is done. The API consumer creates a pact file that defines the expected request and response for each API endpoint, and the API provider uses this pact file to write tests that ensure the API adheres to the contract.

Example of contract testing using the Pact framework in Python:

# API consumer test
from pactman import Consumer, Provider

pact = Consumer('My Consumer').has_pact_with(Provider('My Provider'))

# Define the expected request and response for an API endpoint
@pact.given('the user exists')
def test_user_exists(provider):
provider.add_interaction(
upon_receiving='a request to retrieve a user',
with_request={'method': 'GET', 'path': '/users/1'},
will_respond_with={'status': 200, 'body': {'name': 'John Doe'}}
)

# Run the test
@pact.verify
def test_user_retrieval(pact_verifier):
# Call the API using the client library
response = requests.get('http://localhost:1234/users/1')

# Verify that the API returns the expected response
pact_verifier.verify(response)

This test case is written from the perspective of the API consumer, and it defines the expected request and response for the API endpoint that retrieves a user by ID. The add_interaction method is used to define the expected request and response, and the verify method is used to run the test and ensure that the API adheres to the contract. The test will fail if the API does not adhere to the contract, and the developers can use the failure message to identify and fix the issue.


Download android app Software Testing – Full Stack QE / SDET and get the early access.