Kotlin Multiplatform: Shared Test Resources
Article Summary
Victoria Gonda from Square tackles a tricky KMP problem: Kotlin/Native doesn't support I/O, yet your shared tests need to read fixture files. Here's the workaround that makes it possible.
When migrating duplicated code and tests to Kotlin Multiplatform, Square's team hit a wall with test fixtures. Their shared tests needed to read JSON and binary files, but Kotlin/Native lacks I/O support. This post walks through their solution using the expect/actual pattern and Gradle tasks.
Key Takeaways
- Use expect/actual pattern to define platform-specific resource reading functions
- JVM implementation uses ClassLoader, iOS requires NSBundle with file parsing
- Gradle copy task moves commonTest resources to iOS test bundle location
- Solution enables identical test fixtures across JVM and iOS platforms
By combining expect/actual declarations with a Gradle copy task, you can share test resources across KMP platforms despite Kotlin/Native's I/O limitations.
About This Article
Square's team had binary protobuf test fixture files that needed to work on both JVM and iOS platforms. Kotlin/Native couldn't read these resources natively, so they needed another approach.
Victoria Gonda used the expect/actual pattern to build platform-specific resource readers. Then she set up a Gradle Copy task to move the commonTest resources into the right location in the iOS test bundle.
Both JVM and iOS could now use the same test fixtures without duplicating code. The same unit tests ran on both platforms and verified behavior consistently.