Search code examples
kotlinkotlin-multiplatformkotlin-multiplatform-mobile

Hamcrest and Mockk for Kotlin Multiplatform Mobile


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.


Solution

  • 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.