Square Aug 24, 2021

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

Critical Insight

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.

The iOS implementation includes a clever NSData extension that handles the binary conversion most developers miss.

About This Article

Problem

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.

Solution

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.

Impact

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.

Recent from Square

Related Articles