Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
158: Contract Testing Basics in Kotlin
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:
- Create a Kotlin data class
ProductResponsethat reflects the original contract (price as aDouble). - Write a simulated "Contract Verifier" function. This function should take the
expectedJson(the contract) and theactualJsonResponse(from the provider) as strings. - The verifier should check if the key
"price"exists in both and if the value in the actual response is a validDouble. - Provide a test case where the
actualJsonResponseis{"id": "p1", "price": "$19.99"}. Your verifier should throw aContractViolationExceptionexplaining that the price format has changed from Double to String.
There are no comments for now.