Intro to PACT for .NET Core: Events based systems
This is continuation of PACT for .NET series where I am going to cover usage of pact in event-based systems.
This article assumes the readers will have basic understanding of event-based systems and framework. In case not, then a good place to start can be RabbitMQ Tutorials | RabbitMQ
I will be using the same repo setup that I have used to demonstrate usage in API based systems. I have tried to cover in detail regarding the setup which can be found in previous blog in this series below
Contract testing for APIs: Intro to PACT for .NET Core | by Ajay kumar | Medium
For illustration purposes, we can imagine a scenario, where Result service (Consumer) wants to get informed whenever a student is created.
Now since both Result and Student are separate services, below is the infrastructure that has been implemented in order to make that work.
- I have incorporated RabbitMq library as a messaging service in both the APIs
- Whenever a new student is created using Student service’s (Provider) POST API, we are publishing an event called
StudentCreatedEvent
- Now the above event can be listened by any service which is interested in that event. In this scenario, that service is Result service
- There is a listener defined in the Result service which may perform any operation based on the information received in
StudentCreatedEvent
event. Maybe it wants to store some details of student in the result service which may be used while preparing result, so that they don’t have to depend on Student service every time.
Contract tests in action
Now the first part is where consumer side contract test project defines the contract that consumer service is expecting
Once the contract is defined, a PACT JSON contract file will be generated that will look like below
Now that this file has been created, we need to write test on provider side, which will honour the above created contract.
Provider side code will look something like below. We can see in the image below, line #50 shows the path to contract test file and line #78 shows the verification
One this setup is ready; we can quickly do a dotnet build
to build the project and dotnet test
to test the project. Alternatively, you can run test individually as well. For illustration, below the success result for pact verification for our scenario
Failure case!
Now to test the failure case, we can make some changes in our provider. Lets rename the LastName
field to LName
and rerun the tests.
Lets run the tests and see the results.
As we see in the results above, the error message suggests that LastName
field is missing at provider side.
For reference, the code repository being discussed is available on github link: https://github.com/ajaysskumar/pact-net-example
Thanks for reading through. Please share feedback, if any, in comments or on my email ajay.a338@gmail.com.