In simple terms, it is an agreement between the service consumer (Client application) and service provider (WebApi).
Why Do We Need Consumer Driven Contract Testing?
As we are moving towards micro services architecture, the client and provider rely on contracts. Both the applications are loosely coupled. If provider modifies the contract without informing the client, then it will break the application at the client end.
Most of the times, consumer application and provider application are owned by different teams. If we want to test the contracts, then it will be a pain. To mitigate this problem, we need to involve both the teams (Consumer and Service team) for integration testing. But this process is very costly, dependency on other teams and is time consuming.
To resolve the above issue, we can use pact tool for contract testing.
Pact: It is a tool for contract testing. For dotnet, we can use “PactNet”.
How Does It Work?
It works in 2 steps. For more details, check out url (https://docs.pact.io/documentation/).
Step 1 - Consumer End
- Setup fake service with the help of pact.
- Mock request and response for the API call.
- Call the
Client method from pact test class.
- Client calls the fake service and it will return the fake response.
- It will generate a json file with complete details of request and response.
- Share this json file with provider.
Step 2 - Provider End
- Read request and response from json files.
- Pact tests replay all the requests with actual API.
- Pact will verify all the responses.
You can download the pact application from github (https://github.com/Head-Strong/Pact.Test.git).
Solution Overview: It consist of three projects:
Provider.Test: Provider tests
Test.Pact.App: Consumer tests
Setup fake service at consumer end:
It will create a json file with name as “clientname”-“providername”.json.
Pact Test Scenario at Consumer Side.
After running these tests, it will generate a json file. Structure of Json file is as follows:
Replay scenario at Provider side.
This above code reads the json file and replays all the scenarios by calling the actual service.
Benefits of Pact
- Removes manual testing efforts
- Less error prone
- Removes dependency of other teams
- Quick feedback