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
116: Testing Shared KMP Code
I remember the first time I tried to run a test in a KMP project and it just... didn't run. I had my logic in commonMain, and I instinctively wrote my test in the JVM source set because that's where my IDE's "Run" button felt most comfortable. It worked for Android, sure, but I was completely ignoring the iOS side. That's the trap of KMP testing: it's easy to accidentally write "platform-specific tests for shared code," which totally defeats the purpose of sharing the code in the first place.
Where do I actually put this?
Let's say we've built a PasswordValidator in commonMain. It's simple logic: it checks for a minimum length and the presence of a digit. I'll start by writing a test for it.
// commonMain
class PasswordValidator {
fun isValid(password: String): Boolean {
return password.length >= 8 && password.any { it.isDigit() }
}
}
Now, if I put my test in jvmTest, I'm only verifying the JVM bytecode. If there's some weird edge case in how Kotlin/Native handles strings on iOS, I'll never find it until a user reports a crash. So, I'm moving the test to commonTest. This is the "magic" folder where tests are written once and executed on every target platform you've defined in your Gradle build.
// commonTest
import kotlin.test.Test
import kotlin.test.assertTrue
import kotlin.test.assertFalse
class PasswordValidatorTest {
@Test
fun testValidPassword() {
val validator = PasswordValidator()
assertTrue(validator.isValid("Secret123"), "Should be valid")
}
@Test
fun testTooShort() {
val validator = PasswordValidator()
assertFalse(validator.isValid("Sec1"), "Should be too short")
}
}
I hit run. On the JVM, it's fast. On the iOS simulator, it takes a few seconds longer to boot the environment, but it passes. Now I have peace of mind across the board without writing the same test twice.
The "Expect" Problem
It's not all smooth sailing, though. What happens when my shared logic depends on something platform-specific? Let's say my PasswordValidator needs to log failed attempts to the system console using an expect function.
// commonMain
expect fun logError(message: String)
class PasswordValidator {
fun isValid(password: String): Boolean {
val valid = password.length >= 8 && password.any { it.isDigit() }
if (!valid) logError("Invalid password attempt")
return valid
}
}
The moment I added that expect fun, my commonTest started screaming. The compiler is basically saying, "I can't run this test in common because I don't know what logError actually does yet."
I could provide the actual implementation in androidMain and iosMain, but that's a problem for the production app, not the test. I don't actually want to spam the system logs every time my CI pipeline runs tests. I need a way to "fake" the platform behavior during the test phase.
Bridging the gap with Test Source Sets
Here is where I realized I could leverage the source set hierarchy. If I want a specific behavior for logError during tests, I can't just put it in commonTest because commonTest is where the tests live, not necessarily where the platform implementations for those tests live.
I have two choices here. The "quick and dirty" way is to provide a dummy actual implementation in the platform source sets. But the professional way—the way that keeps your production code clean—is to use an interface or a dependency injection pattern so I can swap the logger for a mock in my tests.
Let's pivot. Instead of a global expect fun, I'll pass a logger into the validator:
// commonMain
interface Logger {
fun log(message: String)
}
class PasswordValidator(private val logger: Logger) {
fun isValid(password: String): Boolean {
val valid = password.length >= 8 && password.any { it.isDigit() }
if (!valid) logger.log("Invalid password attempt")
return valid
}
}
Now, in commonTest, I can just create a MockLogger. Since the MockLogger is just a standard Kotlin class, it doesn't need any actual implementations. It works everywhere.
// commonTest
class MockLogger : Logger {
var lastLog: String? = null
override fun log(message: String) {
lastLog = message
}
}
@Test
fun testLoggingOccursOnFailure() {
val mockLogger = MockLogger()
val validator = PasswordValidator(mockLogger)
validator.isValid("short")
assertEquals("Invalid password attempt", mockLogger.lastLog)
}
By moving away from expect/actual for things that can be abstracted into interfaces, I've made my shared tests truly platform-independent. I'm no longer fighting the compiler; I'm just writing standard Kotlin.
📋 Practical Task
Exercise: Building a Multiplatform UUID Generator Test
You are tasked with testing a SessionManager class that lives in commonMain. This class requires a UuidGenerator to create unique session IDs.
Requirements:
- Create an interface
UuidGeneratorincommonMainwith a functiongenerate(): String. - Create a
SessionManagerclass incommonMainthat takes aUuidGeneratorin its constructor. It should have a functioncreateSession()that returns a string in the format:"SESSION_ID: [uuid]". - In
commonTest, create aFakeUuidGeneratorthat always returns the hardcoded string"1234-5678". - Write a test in
commonTestthat verifiescreateSession()returns exactly"SESSION_ID: 1234-5678".
Goal: Ensure the test runs in the commonTest source set so it validates the session logic across all target platforms without needing platform-specific actual implementations for the UUID generation.
There are no comments for now.