Sharing tests across Kotlin Multiplatform (KMP) projects can be tricky when dealing with platform-specific APIs like Android’s Bundle. commonTest on Android relies on the androidTest source set, which uses an empty android.jar, leading to test failures.

The Solution

The ideal solution is to avoid platform-specific APIs in commonTest.

If that’s not an option, you can use Robolectric in your commonTest source set to access functional Android classes. This approach:

  • Allows testing of platform-specific code in commonTest.
  • Eliminates the need to duplicate tests in androidTest.

How It’s Done

  1. Add the Robolectric dependency to your androidTest :
implementation("org.robolectric:robolectric:4.14")
  1. Use expect/actual to provide platform-specific abstract class RobolectricTest.

In commonTest, define the expect class:

expect abstract class RobolectricTest()

In androidTest, provide the actual implementation using Robolectric:

@RunWith(RobolectricTestRunner::class)
@Config(manifest = Config.NONE)
actual abstract class RobolectricTest actual constructor()

For other platforms, provide an empty actual implementation:

actual abstract class RobolectricTest actual constructor()
  1. Write your tests in commonTest extending the expected declaration.
class SavedStateTest : RobolectricTest()

That’s It

Robolectric will simulate the Android environment and allow a commonTest to run platform-specific code.

ℹ️ If you enjoyed the article you might enjoy following me on Bluesky. ℹ️

References