DEV Community

Cover image for Consumer Driven Contract Testing - Hosting A Mocked API Using Azure Functions
Christian Eder
Christian Eder

Posted on

Consumer Driven Contract Testing - Hosting A Mocked API Using Azure Functions

Applying the concept of Consumer Driven Contract Testing is useful when you are building a system that is composed of multiple decoupled services. Some of these services will provide APIs, others will consume these APIs. Consumer Driven Contract Testing is about the API consumer publishing their expectations on the API in a way that allows

  • the provider of the API to verify that that it fulfils these expectations
  • the consumer of the API to easily stand up a mock of the provider API to run their own tests against

If you are not already familiar with the concept, you can dive deeper into the topic by reading Frank Rosner's excellent article or visit PACT is one of the major libraries available to implement Consumer Driven Contract Tests. The examples shown in this article however are based on the Impact library.

The basic idea is, that the consuming service defines a so called Pact that codifies the consumers expectations on the API structure & behavior:

The Pact shown in the example above defines an HTTP API that responds to any GET request to an URL with a path matching weatherforecast\/([a-zA-Z]+)\/(\d+) and responds with weather forecast data.

Based on this Pact, the consumer can stand up a test server on localhost and run tests of the consuming service using this mocked API:

After successfully running its own tests against this mocked API, the consumer can publish the PACT to the provider as a JSON file:

The provider can now take this JSON file and run the expectations defined in that file against its own API:

Hosting the mocked API on an Azure Function

If the consuming service does not want to run the mocked provider API on localhost - e.g. because it wants to run its own tests against a cloud hosted environment - we need a way to host the MockServer in the cloud as well. The following code snippet shows a fully working example of an Azure Function that will host an HTTP endpoint which will respond to any request as defined in the Pact:

You can find the whole example (and more) on my GitHub repo

Discussion (0)