Kotlin Multiplatform Testing: Shared Tests, expect/actual, and Platform Fixtures
Kotlin Multiplatform lets you write business logic once and run it on Android, iOS, desktop, and server. Testing KMP code requires understanding the expect/actual mechanism for test utilities, how to share fixtures across platforms, and how platform-specific tests differ from shared ones.
Kotlin Multiplatform (KMP) is increasingly the default choice for shared mobile logic: networking, data parsing, business rules, repository layers. The promise is compelling — write once, test once, run everywhere. The reality is more nuanced. You can share most tests, but platform differences require deliberate design.
This guide focuses on testing: how to structure tests for maximum reuse, how to use expect/actual in test code, and how to handle the parts that are inherently platform-specific.
Project Structure
A typical KMP module looks like this:
shared/
├── src/
│ ├── commonMain/kotlin/ # Shared production code
│ ├── commonTest/kotlin/ # Shared tests (run on all platforms)
│ ├── androidMain/kotlin/ # Android-specific implementations
│ ├── androidTest/kotlin/ # Android-specific tests
│ ├── iosMain/kotlin/ # iOS-specific implementations
│ └── iosTest/kotlin/ # iOS-specific testsTests in commonTest run on every platform. They are compiled and executed for Android JVM, iOS (via Kotlin/Native), and any other targets you configure.
// shared/build.gradle.kts
kotlin {
androidTarget()
iosX64()
iosArm64()
iosSimulatorArm64()
sourceSets {
commonTest.dependencies {
implementation(kotlin("test"))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.8.1")
}
androidUnitTest.dependencies {
implementation("io.mockk:mockk:1.13.11")
}
}
}Writing Shared Tests in commonTest
Tests in commonTest use kotlin-test, which provides a platform-agnostic assertion API. The test runner varies by platform (JUnit on JVM, XCTest runner on iOS), but the test code is identical.
// commonTest/kotlin/com/example/UserValidatorTest.kt
class UserValidatorTest {
private val validator = UserValidator()
@Test
fun `valid email passes validation`() {
val result = validator.validate(
User(name = "Alice", email = "alice@example.com", age = 25)
)
assertTrue(result.isValid)
assertTrue(result.errors.isEmpty())
}
@Test
fun `empty name fails validation`() {
val result = validator.validate(
User(name = "", email = "alice@example.com", age = 25)
)
assertFalse(result.isValid)
assertTrue(result.errors.contains("Name is required"))
}
@Test
fun `underage user fails validation`() {
val result = validator.validate(
User(name = "Bob", email = "bob@example.com", age = 16)
)
assertFalse(result.isValid)
assertEquals("Must be 18 or older", result.errors.first())
}
@Test
fun `invalid email fails validation`() {
listOf("notanemail", "missing@dot", "@nodomain.com").forEach { email ->
val result = validator.validate(
User(name = "Carol", email = email, age = 20)
)
assertFalse(result.isValid, "Expected failure for email: $email")
}
}
}kotlin-test assertions:
assertEquals(expected, actual)/assertNotEqualsassertTrue(condition)/assertFalseassertNull(value)/assertNotNullassertContentEquals(expected, actual)— for arrays and collectionsassertFails { block }— verifies a block throws any exceptionassertFailsWith<T> { block }— verifies a specific exception type
expect/actual in Test Code
expect/actual is not just for production code. You can use it in tests to define platform-specific test utilities while keeping the test logic shared.
Shared Test Utilities
A common need: create a test database, run tests, tear it down. The creation is platform-specific; the tests are shared.
// commonTest/kotlin/TestDatabase.kt
expect class TestDatabase() {
fun insert(table: String, values: Map<String, Any>)
fun query(sql: String): List<Map<String, Any>>
fun clear()
fun close()
}
// androidTest/kotlin/TestDatabase.android.kt
actual class TestDatabase actual constructor() {
private val db = Room.inMemoryDatabaseBuilder(
ApplicationProvider.getApplicationContext(),
AppDatabase::class.java
).build()
actual fun insert(table: String, values: Map<String, Any>) {
// Room-specific implementation
}
actual fun query(sql: String): List<Map<String, Any>> {
return db.openHelper.readableDatabase.rawQuery(sql, null).use { cursor ->
// Convert cursor to list of maps
cursor.toMapList()
}
}
actual fun clear() = db.clearAllTables()
actual fun close() = db.close()
}
// iosTest/kotlin/TestDatabase.ios.kt
actual class TestDatabase actual constructor() {
private val connection = SQLiteDatabase(":memory:")
actual fun insert(table: String, values: Map<String, Any>) {
// SQLite.swift or SQLDelight-based implementation
}
actual fun query(sql: String): List<Map<String, Any>> {
return connection.executeQuery(sql)
}
actual fun clear() = connection.execute("DELETE FROM sqlite_master WHERE type='table'")
actual fun close() = connection.close()
}Now the shared test uses this without knowing which platform it runs on:
// commonTest/kotlin/UserRepositoryTest.kt
class UserRepositoryTest {
private lateinit var db: TestDatabase
private lateinit var repo: UserRepository
@BeforeTest
fun setUp() {
db = TestDatabase()
repo = UserRepository(db)
}
@AfterTest
fun tearDown() {
db.close()
}
@Test
fun `saves and retrieves user`() {
val user = User(id = 0, name = "Alice", email = "alice@test.com")
val saved = repo.save(user)
assertNotEquals(0, saved.id)
assertEquals(saved, repo.findById(saved.id))
}
@Test
fun `findAll returns all saved users`() {
repo.save(User(id = 0, name = "Alice", email = "alice@test.com"))
repo.save(User(id = 0, name = "Bob", email = "bob@test.com"))
val all = repo.findAll()
assertEquals(2, all.size)
}
}Platform-Specific Clock for Time-Sensitive Tests
// commonTest/kotlin/TestClock.kt
expect object TestClock {
var currentTimeMs: Long
fun advance(ms: Long)
fun reset()
}
// jvmTest/kotlin/TestClock.jvm.kt
actual object TestClock {
actual var currentTimeMs: Long = 0L
actual fun advance(ms: Long) { currentTimeMs += ms }
actual fun reset() { currentTimeMs = 0L }
}
// iosTest/kotlin/TestClock.ios.kt
actual object TestClock {
actual var currentTimeMs: Long = 0L
actual fun advance(ms: Long) { currentTimeMs += ms }
actual fun reset() { currentTimeMs = 0L }
}// commonMain/kotlin/SessionManager.kt — uses injected clock
class SessionManager(private val clock: () -> Long = { TestClock.currentTimeMs }) {
private var loginTime: Long = 0
fun login() { loginTime = clock() }
fun isSessionExpired(timeoutMs: Long = 30 * 60 * 1000): Boolean {
return clock() - loginTime > timeoutMs
}
}
// commonTest/kotlin/SessionManagerTest.kt
class SessionManagerTest {
@BeforeTest
fun setUp() = TestClock.reset()
@Test
fun `session is valid immediately after login`() {
val manager = SessionManager(clock = { TestClock.currentTimeMs })
manager.login()
assertFalse(manager.isSessionExpired())
}
@Test
fun `session expires after timeout`() {
val manager = SessionManager(clock = { TestClock.currentTimeMs })
manager.login()
TestClock.advance(31 * 60 * 1000) // 31 minutes
assertTrue(manager.isSessionExpired())
}
}Coroutine Testing in KMP
runTest works in commonTest. The coroutine test library is multiplatform-ready:
// commonTest/kotlin/ProductServiceTest.kt
class ProductServiceTest {
private val fakeRepo = FakeProductRepository()
private val service = ProductService(fakeRepo)
@Test
fun `loadProducts returns sorted list`() = runTest {
fakeRepo.setProducts(listOf(
Product(id = 2, name = "Z Product", price = 10.0),
Product(id = 1, name = "A Product", price = 20.0)
))
val products = service.loadProducts()
assertEquals("A Product", products.first().name)
assertEquals("Z Product", products.last().name)
}
@Test
fun `loadProducts throws on network failure`() = runTest {
fakeRepo.setError(NetworkException("No connection"))
assertFailsWith<NetworkException> {
service.loadProducts()
}
}
}Fake Repositories in commonTest
Avoid MockK in commonTest — it uses JVM reflection and doesn't work on iOS. Write explicit fakes instead:
// commonTest/kotlin/fakes/FakeProductRepository.kt
class FakeProductRepository : ProductRepository {
private var products: List<Product> = emptyList()
private var error: Throwable? = null
fun setProducts(products: List<Product>) {
this.products = products
this.error = null
}
fun setError(error: Throwable) {
this.error = error
this.products = emptyList()
}
override suspend fun getAll(): List<Product> {
error?.let { throw it }
return products
}
override suspend fun getById(id: Int): Product? {
error?.let { throw it }
return products.find { it.id == id }
}
override suspend fun save(product: Product): Product {
error?.let { throw it }
val saved = product.copy(id = products.size + 1)
products = products + saved
return saved
}
}The fake is fully shared across platforms. Android-specific tests can also use it, or they can use MockK for more complex scenarios.
Sharing Test Fixtures
Test fixtures — sample data, builders, factory functions — live in commonTest and are available everywhere:
// commonTest/kotlin/fixtures/ProductFixtures.kt
object ProductFixtures {
fun aProduct(
id: Int = 1,
name: String = "Test Product",
price: Double = 9.99,
category: Category = Category.ELECTRONICS,
inStock: Boolean = true
) = Product(
id = id,
name = name,
price = price,
category = category,
inStock = inStock
)
fun aProductList(count: Int = 5) = (1..count).map { i ->
aProduct(id = i, name = "Product $i", price = i * 10.0)
}
fun anOutOfStockProduct() = aProduct(inStock = false, name = "Sold Out Product")
}
// commonTest/kotlin/fixtures/UserFixtures.kt
object UserFixtures {
fun aUser(
id: Int = 1,
name: String = "Alice",
email: String = "alice@example.com",
role: Role = Role.USER
) = User(id = id, name = name, email = email, role = role)
fun anAdmin() = aUser(role = Role.ADMIN, name = "Admin User")
}Using fixtures in tests:
class CartServiceTest {
private val fakeRepo = FakeProductRepository()
private val cart = CartService(fakeRepo)
@Test
fun `add product increases total`() = runTest {
fakeRepo.setProducts(ProductFixtures.aProductList(3))
cart.addProduct(productId = 1, quantity = 2)
assertEquals(20.0, cart.getTotal()) // Product 1 costs 10.0 * 2
}
@Test
fun `cannot add out of stock product`() = runTest {
val outOfStock = ProductFixtures.anOutOfStockProduct()
fakeRepo.setProducts(listOf(outOfStock))
assertFailsWith<OutOfStockException> {
cart.addProduct(productId = outOfStock.id, quantity = 1)
}
}
}Platform-Specific Tests
Some things genuinely cannot be tested in commonTest. Android-specific UI, iOS-specific APIs, and reflection-heavy mocking belong in platform-specific source sets.
// androidUnitTest/kotlin/com/example/AndroidSpecificTest.kt
class AndroidSpecificTest {
@Test
fun `formats currency using Android locale`() {
val formatter = AndroidCurrencyFormatter(Locale.US)
assertEquals("$9.99", formatter.format(9.99))
}
@Test
fun `parses deep link intent correctly`() {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("myapp://product/42"))
val parsed = DeepLinkParser.parse(intent)
assertEquals(DeepLink.ProductDetail(productId = 42), parsed)
}
}// iosTest/kotlin/com/example/IosSpecificTest.kt
class IosSpecificTest {
@Test
fun `formats currency using iOS locale`() {
val formatter = IosCurrencyFormatter(NSLocale("en_US"))
assertEquals("$9.99", formatter.format(9.99))
}
}Running Tests
# Run all tests on all platforms
./gradlew :shared:allTests
# Run only common tests (JVM)
./gradlew :shared:jvmTest
# Run Android unit tests
./gradlew :shared:testDebugUnitTest
# Run iOS tests (requires macOS + Xcode)
./gradlew :shared:iosSimulatorArm64TestFor CI, run allTests on macOS to include iOS. On Linux/Windows, run jvmTest and androidUnitTest for the cross-platform and Android-specific tests.
Key Takeaways
commonTestis the primary test location — most business logic tests belong there. Platform-specific test folders are for exceptions, not the rule.- Use fakes, not mocks, in
commonTest— MockK and Mockito use JVM reflection and fail on Kotlin/Native (iOS). Write explicit fake implementations instead. expect/actualin tests enables shared test logic with platform-specific setup — database creation, file system access, and network stubs can all be abstracted this way.- Fixtures in
commonTestserve all platforms — write your test data builders once and reuse them in Android instrumentation tests, iOS tests, and everything else. runTestworks incommonTest— coroutine tests are fully portable across platforms.- Don't fight the platform boundary — Android UI tests and iOS UI tests must be platform-specific. Share as much as possible above that layer.