使用多平台模拟 kotlin 中的常见测试

mock common tests in kotlin using multiplatform

我无法将通用模拟库 ( mockk.io ) 与 kotlin 多平台一起使用。在他们的网站上说,要在 kotlin 多平台中使用 mockk,您只需将此行添加到您的 gradle。 testImplementation "io.mockk:mockk-common:{version}"

我添加了它并且它正常构建,只有当我想使用它时它才会失败。给予

Unresolved reference: io
Unresolved reference: mockk

我的gradle文件


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")
            }
        }
    }
}

除非发生某些变化,否则 mockk 不适用于 Kotlin Native。

您可以使用 Mockative 模拟 Kotlin/Native 和 Kotlin Multiplatform 中的接口,这与使用 MockK 或 Mockito 模拟依赖项的方式不同。

完全披露:我是 Mockative 的作者之一

这是一个例子:

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)
    }
}