Skip to Content
Course content

223: Contract Testing Between Scala Microservices

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Why can't I just rely on integration tests for this?

I get this question all the time. In a perfect world, spinning up every microservice in a staging environment and running a suite of integration tests would be enough. But as your system grows, that approach becomes a nightmare. You end up with a "distributed monolith" where you can't deploy the PaymentService because the OrderService is currently broken in staging, which blocks your tests.

Integration tests are slow and flaky. Contract testing flips the script. Instead of testing the implementation of two services together, we test the agreement between them. We verify that the Consumer (the one calling the API) and the Provider (the one serving the API) still speak the same language. If the PaymentService changes a field from transaction_id to tx_id, a contract test will catch that in the Provider's CI pipeline long before it ever reaches a shared environment.

How do I actually implement a "Consumer-Driven" contract in Scala?

The "Consumer-Driven" part means the service that needs the data defines the requirements. In the Scala ecosystem, we typically use Pact. The consumer writes a test that defines the expected response and then generates a "pact file" (a JSON contract).

Imagine our OrderService needs to check a payment status. Instead of mocking the PaymentService with a hardcoded string that might be outdated, we define the expectation. Here is a simplified look at how you'd structure that expectation using a Pact-like DSL in Scala:

import au.com.saxon.pact.consumer.PactDsl
import au.com.saxon.pact.consumer.Pact

// Define the contract for the Payment Status endpoint
val paymentContract = Pact.create("OrderService", "PaymentService")
  .uponReceiving("A request for payment status")
  .path("/payments/status/123")
  .method("GET")
  .willRespondWith()
  .status(200)
  .body(PactDsl.newJsonBody()
    .stringType("paymentId", "PAY-123")
    .stringType("status", "COMPLETED")
    .integerType("amountCents", 5000))
  .toPact()

The key here is stringType. We aren't testing for the exact value "PAY-123", but rather that the field paymentId exists and is a string. This keeps the contract flexible but firm on the data types.

What happens on the Provider side to make this useful?

Generating the JSON file is only half the battle. The real magic happens when the PaymentService (the Provider) pulls that pact file during its own build process. The Provider doesn't need the Consumer to be running; it just needs the contract.

The Provider's test runner reads the pact file, plays the requested call (GET /payments/status/123) against the local running instance of the service, and compares the actual response to the expected one. If the Provider's code returns an integer for paymentId instead of a string, the test fails.

I've seen teams try to do this manually with shared JSON schemas, but that usually fails because schemas are often too broad. Consumer-driven contracts are better because they only test the fields the consumer actually uses. If the Provider adds ten new fields to the response, the contract test still passes because the Consumer doesn't care about those extra fields. It only cares that the ones it depends on are still there.

How do I handle versioning when the contract has to change?

This is where things get spicy. You can't just change the contract and break the Provider's build; you'll stop everyone from deploying. The workflow should be:

  • The Consumer updates the contract to include a new field or change a type.
  • The Consumer publishes the new version of the pact (usually to a "Pact Broker").
  • The Provider sees the new contract failing in their CI.
  • The Provider implements the change to satisfy the new contract while maintaining backward compatibility for older versions of the consumer.
  • Once the Provider is updated, the Consumer deploys the version of the code that relies on the new contract.

It sounds like a lot of overhead, but it's a thousand times better than the "deploy and pray" method where you find out about a breaking change via a 500-error spike in your production logs.




📋 Practical Task

Exercise: Breaking and Fixing the Payment-Order Contract

You have been provided with a Scala project containing two modules: order-service (Consumer) and payment-service (Provider). Currently, they are in sync, and the contract tests pass.

Your goal:

  1. Navigate to the payment-service and rename the JSON field amountCents to totalAmountCents in the response case class.
  2. Run the Provider verification tests and observe the contract failure. Analyze the error message to identify exactly which field the order-service is missing.
  3. Instead of just renaming it back, implement a "grace period" strategy: modify the payment-service to return both the old amountCents and the new totalAmountCents fields in the JSON response.
  4. Run the verification tests again to ensure the contract is satisfied while the Provider evolves its API.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.