Hamcrest and Mockk for Kotlin Multiplatform Mobile

Viewed 1238

I am trying to write tests in the shared module of a KMM project. In the shared module's build.gradle.kts file I have the following:

sourceSets {
    val commonMain by getting
    val commonTest by getting {
        dependencies {
            implementation(kotlin("test-common"))
            implementation(kotlin("test-annotations-common"))


            //TODO: Hamcrest
            //implementation("junit:junit:4.12")
            //implementation("org.hamcrest:hamcrest-library:1.3")

            //TODO: Mockk
            //implementation("io.mockk:mockk:1.10.4")
        }
    }
    //...
}

I have also tried:

implementation(kotlin("[library]"))

with the same result: The tests are no longer recognised by the IDE and I cannot run them.

2 Answers

Unfortunately there isn't a mocking library that has K/N support (AFAIK).

Here's Mockk's K/N and Mockk's K/JS issue for future reference or you could also check out Touchlab's Karmok

For Hamcrest, see their issue here

Edit/Update

In 2022 above answer doesn't stand true anymore. Mockk now supports mocking in shared modules. Please check here mockk.io Add the following dependency and you should be good to go

testImplementation "io.mockk:mockk-common:{version}"

The mocking experience is seamless, just like a regular Android unit test case.

I got a response from the KMM team - thought I would put it here for reference

You can use only multiplatform dependencies that support all declared targets in common source-set, because this could will be used for compilation for all the targets. Junit is not a multiplatform library, it’s JVM, so you should add it to your jvm target source-set (androidMain if you declared android() target). Check this project: https://github.com/Kotlin/kmm-sample/blob/master/shared/build.gradle.kts for example.

The same issue relates to other dependencies - they are not multiplatform, so you can’t use them in a commons source-set.

Related