Skip to Content
Course content

158: Contract Testing Basics in Kotlin

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

I've seen this exact scenario play out in more than one production outage. You've got a frontend team (or a separate microservice) and a backend team. Both are writing tests. Both tests are passing. And yet, the moment the code hits the staging environment, the whole thing crashes with a NullPointerException or a JSON parsing error. Here is a classic example of how that happens in Kotlin.

// Consumer Side (e.g., an Order Service)
data class UserProfile(val userId: String, val username: String)

class UserClient(private val httpClient: HttpClient) {
    fun getUser(id: String): UserProfile {
        val response = httpClient.get("/users/$id")
        // This fails at runtime because 'username' is missing from the JSON
        return Json.decodeFromString<UserProfile>(response.body)
    }
}

// The "passing" Consumer Test
@Test
fun `should fetch user profile`() {
    val mockClient = mockk<HttpClient>()
    every { mockClient.get(any()) } returns HttpResponse(
        body = """{"userId": "123", "username": "kotlin_dev"}"""
    )
    
    val client = UserClient(mockClient)
    val profile = client.getUser("123")
    
    assertEquals("kotlin_dev", profile.username)
}

The "Mocking Lie" that breaks production

If you look at that test, it looks perfect. It's fast, it's isolated, and it passes. But here is the problem: the consumer is testing against a lie. The mock is based on what the developer thinks the API looks like, not what the API actually looks like.

Meanwhile, over on the Provider side (the User Service), a developer decided to rename username to handle to better align with the new branding. They updated their own tests, the tests passed, and they pushed to production. Neither side knew the contract was broken until the services tried to talk to each other in the wild.

Bridging the gap with Consumer-Driven Contracts

To fix this, we stop guessing. Instead of the consumer just making up a mock, we use Contract Testing (often using a tool like Pact). The core idea is that the consumer defines a "contract" (a JSON file) that says: "If I send you a GET request to /users/123, I expect a 200 OK with a body containing a string called 'username'."

This contract is then shared with the provider. The provider's build pipeline automatically runs a test that replays the requests in the contract against the actual running service. If the provider renamed the field to handle, the contract test fails immediately on the provider's machine—long before the code ever reaches a shared environment.

// Using a Pact-like DSL in Kotlin to define the contract
val pact = consumer("OrderService")
    .hasPactWith("UserService")
    .uponReceiving("a request for user profile")
    .path("/users/123")
    .method("GET")
    .willRespondWith()
    .status(200)
    .body(newJsonBody {
        string("userId", "123")
        string("username", "kotlin_dev") // The Provider MUST provide this exact key
    })
    .toPact()

Enforcing the truth on the Provider side

Now, the provider doesn't just hope they are doing the right thing. They incorporate the contract into their test suite. In a real-world Kotlin setup, you'd use a Pact Verifier. When the provider runs their tests, the verifier reads that JSON contract, hits the local provider endpoint, and compares the actual response to the expected one.

The fix isn't just a code change; it's a workflow change. If the provider needs to rename username to handle, they can't just do it. They first have to notify the consumer, who updates the contract. The provider's tests will fail until they implement the change, and the consumer's tests will fail until they update their data classes. The contract becomes the "single source of truth" that prevents the two services from drifting apart.




📋 Practical Task

Exercise: Detecting a Breaking Change in the Product API

You are working on a system where a StorefrontService (Consumer) depends on a CatalogService (Provider). The current contract expects the product price to be a Double, but the Catalog team has changed it to a String (to include currency symbols like "$19.99"), which will crash the Storefront's JSON parser.

Your Task:

  1. Create a Kotlin data class ProductResponse that reflects the original contract (price as a Double).
  2. Write a simulated "Contract Verifier" function. This function should take the expectedJson (the contract) and the actualJsonResponse (from the provider) as strings.
  3. The verifier should check if the key "price" exists in both and if the value in the actual response is a valid Double.
  4. Provide a test case where the actualJsonResponse is {"id": "p1", "price": "$19.99"}. Your verifier should throw a ContractViolationException explaining that the price format has changed from Double to String.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.