4

I can't use the common mock library ( mockk.io ), with kotlin multiplatform. In their website it says that to use mockk in kotlin multiplatform you just need to add this line to your gradle. testImplementation "io.mockk:mockk-common:{version}"

I added it and it builds normally, only when I want to use it is when it fails. Giving

Unresolved reference: io
Unresolved reference: mockk

my gradle file


kotlin {
    val hostOs = System.getProperty("os.name")
    val isMingwX64 = hostOs.startsWith("Windows")
    val nativeTarget = when {
        hostOs == "Mac OS X" -> macosX64("native")
        hostOs == "Linux" -> linuxX64("native")
        isMingwX64 -> mingwX64("native")
        else -> throw GradleException("Host OS is not supported in Kotlin/Native.")
    }

    nativeTarget.apply {
        binaries {
            executable {
                entryPoint = "main"
            }
        }
    }
    sourceSets {
        val nativeMain by getting
        val nativeTest by getting
        val commonTest by getting {
            dependencies {
                implementation(kotlin("test-common"))
                implementation(kotlin("test-annotations-common"))
                implementation("io.mockk:mockk-common:1.10.4")
            }
        }
    }
}
saykou
  • 167
  • 1
  • 9

2 Answers2

6

Unless something has changed, mockk does not work on Kotlin Native.

Kevin Galligan
  • 16,159
  • 5
  • 42
  • 62
  • Yeah, that is what I also was trying to understand. I have a native target but I also have common code. I believe that mockk works with common code and common test right ? – saykou Dec 30 '20 at 08:20
  • If your common code is intended to run on native, then no. It won't work if there's no native implementation. – Kevin Galligan Dec 30 '20 at 22:48
  • https://github.com/mockk/mockk/issues/58 -> For future reference – Róbert Nagy Jan 04 '21 at 14:04
3

You can use Mockative to mock interfaces in Kotlin/Native and Kotlin Multiplatform, not unlike how you'd mock dependencies using MockK or Mockito.

Full disclosure: I am one of the authors of Mockative

Here's an example:

class GitHubServiceTests {
    @Mock val api = mock(classOf<GitHubAPI>())

    val service = GitHubService(api)

    @Test
    fun test() {
        // Given
        val id = "mockative/mockative"
        val mockative = Repository(id = id, name = "Mockative")
        given(api).invocation { fetchRepository(id) }
            .thenReturn(mockative)

        // When
        val repository = service.getRepository(id)

        // Then
        assertEquals(mockative, repository)

        // You can also verify function calls on mocks
        verify(api).invocation { fetchRepository(id) }
            .wasInvoked(exactly = once)
    }
}
Nicklas Jensen
  • 1,424
  • 12
  • 19