Skip to Content
Course content

116: Testing Shared KMP Code

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

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 UuidGenerator in commonMain with a function generate(): String.
  • Create a SessionManager class in commonMain that takes a UuidGenerator in its constructor. It should have a function createSession() that returns a string in the format: "SESSION_ID: [uuid]".
  • In commonTest, create a FakeUuidGenerator that always returns the hardcoded string "1234-5678".
  • Write a test in commonTest that verifies createSession() 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.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.