Skip to content

Craftsmanship

Software Factory

Consumer-Driven Contract testing made simple with Pact (Part 2/3)

27 Aug 2019

by

Yoan Thirion

Start Consumer-Driven Contract testing with Pact!

What is Pact ?

Pact is a contract testing tool. Contract testing is a way to ensure that services (such as an API provider and a client) can communicate with each other. Without contract testing, the only way to know that services can communicate is by using expensive and brittle integration tests.

Pact provides a testing button for your code, allowing you to safely confirm that your applications will work together without having to deploy the world first.

It is available on a lot of platforms and languages :

1*ExvTh_J5gK1SAOJbQkoHkg

Pact comes with its own specification regarding the format of the contracts between consumers and providers :

0*Qo9oDa-4ngA-UiDm

How can we implement a new service with Pact ?

Because we use a CDC approach we start with the consumer and here is what we want as a consumer :

As a consumer, I want a Rest API that returns "Hello world v1" when I GET "api/v1.0/helloworld"

1) Start with the consumer

Let's implement a simple consumer by :

  • Writing Test(s)
  • Define interactions / Expectations
1*4Mk1PuPznY1xqOMebCicwg

Concretely :

  • Build your client : here we call it consumer-js
1*2I-kxQiqRAAjOU6YmmrMDg

  • Describe and configure the interactions (behaviors and expectations)
1*BxXKKMSs76MEFhW3HzrSDg

Once you have defined it you can run the tests. From those expectations Pact will create a contract file : a JSON file that will look like this :

1*AKA8DjGzo59vFVyVDWLPZA

2) Contract Driven Development

  • Design Your API From The Contract
  • Write a RED test
1*fi-yU8DIvzJIBTlDMyZMRg

The RED test (in .NET Core)

0*1JTWJB1WP13Bk0DH

The test will be launched and interactions will be verified based on the contract that has been defined on the consumer side.

1*bxG9GR41_jxNk37e8LLLZw

Make the test GREEN

0*D_dKCc7fr3JyCoco

Features offered by Pact

In this simple example we have just checked a GET interaction with simple string matcher but you can achieve much more complex and more realistic verifications with the tool :

1*G7YzQGX36bAxF8jkPDhGuw

S.W.O.T

Based on our experience with Pact here is our S.W.O.T :

1*u-WSLkHX2N81b6a9R0hJ0w

Resources

Please find the code samples in this repository : https://github.com/agilepartner/pact-sandbox

To go further check the implementation guide in your favorite language : https://docs.pact.io/implementation_guides

Conclusion

Pact is a really good tool to start a CDC approach. It is easy to use but there is one problem that needs to be solved before starting using it in enterprise :

Where the hell do we store the contracts?

Want to know more about CDC?