Contract testing is a technique for testing an integration point by checking each application in isolation to ensure the messages it sends or receives conform to a shared understanding that is documented in a "contract".
Consider an e-commerce application with three microservices:
Product Service (A): Manages the product catalog and provides information about available products. Cart Service (B): Handles the shopping cart functionality, allowing users to add and remove items from their cart. Payment Service (C): Handles payment processing for completed orders. Here's how they might communicate:
Product Service (A) communicates with Cart Service (B):
When a user adds a product to their cart, the Cart Service needs to retrieve information about the product. The Cart Service recevice message from the Product Service and product is added to cart.
Cart Service (B) communicates with Payment Service (C):
After the user completes their shopping and proceeds to checkout, the Cart Service needs to initiate payment processing for the items in the cart. The Cart Service sends a message to the Payment Service, providing the total amount to be paid and any relevant order information. The Payment Service receives the request, interacts with payment gateways or external payment processors, and processes the payment transaction.
Once the payment is processed successfully, the Payment Service notifies the Cart Service about the payment status.
We are using masstransit as the messaging service between the microservices.
Pull and run the rabbit mq docker image
docker run -p 15672:15672 -p 5672:5672 masstransit/rabbitmq
Now run the program with multiple project startup by selecting all the services (A,B,C)
A swagger page will open and you can post the requests via swagger and you can see that in the terminals opened
Now you can run the consumer tests like you run the unit tests in the test explorer.
Then a folder named pacts will be created with the contracts file.
Once the pact files are created you need to run the provider tests which takes the contract files as input and verify the contract.
If everything is green then the microservices are communicating as expected.
You can also use broker to make visulation of the contracts verification.
PactBroker can be self-hosted for the local development
https://github.com/pact-foundation/pact-broker-docker.git
Run the docker file via
docker compose up
Run the consumer tests locally and upload the contract files via cli
- Download the latest version of cli
https://github.com/pact-foundation/pact-ruby-standalone/releases
- Upload the contracts via cli
.\pact-broker.bat publish CartService.ConsumerTests\pacts\ -b http://localhost:9292/ --consumer-app-version 1.0
Verify the provider tests via source as pact broker by modifying in the code