You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

KMM shared模块commonTest使用mockk运行测试遇未解析引用错误

KMM shared模块commonTest中MockK方法运行时提示未解析引用的问题

在KMM的shared模块commonTest中导入了MockK库,IDE中测试类没有显示导入错误,但运行测试时,所有使用MockK库方法(如mockk、every、verify)的位置均出现以下错误:

Unresolved reference: every
Unresolved reference: mockk
Unresolved reference: verify

测试代码示例(带错误标记):

class DefaultAppPreferenceStorageTest {

    val appPreference = mockk<AppPreference>() //Unresolved reference: mockk
    val jsonService = mockk<JsonService>() //Unresolved reference: mockk

    val jsonKey = "key"
    val value = 1
    val stringValue = "$value"
    val defaultIntValue = Random.nextInt()

    val storage = DefaultAppPreferenceStorage(
        appPreference,
        jsonService
    )

    inner class PutJsonTest {

        @BeforeTest
        fun beforeEachTest() {
            every { jsonService.mapToString(value) } returns stringValue //Unresolved reference: every

            storage.putJson(jsonKey, value)
        }

        @Test
        fun testPutJson() {
            verify(verifyBlock = { jsonService.mapToString(value) }) //Unresolved reference: verify
            verify(verifyBlock = { appPreference.putString(jsonKey, stringValue) }) //Unresolved reference: verify
        }
    }

    ...
}

更新的依赖配置:

const val mockk = "1.12.5"

const val mockk = "io.mockk:mockk-common:${Version.mockk}"
val commonTest by getting {
    dependencies {
        implementation(kotlin("test"))
        implementation(kotlin("test-common"))
        implementation(kotlin("test-annotations-common"))
        implementation(ShareTestDependencies.mockk)
        implementation(ShareTestDependencies.coroutinesTest)
    }
}

可能的原因及解决方法:

  • 依赖变量定义冲突:你重复定义了const val mockk,第一个是版本号字符串,第二个是依赖坐标。这种重复定义会导致变量覆盖,若Version.mockk引用的是第一个mockk变量,虽然最终依赖坐标格式看似正确,但代码本身存在语法错误,可能导致Gradle解析异常。建议拆分版本号和依赖坐标的定义:
    const val mockkVersion = "1.12.5"
    const val mockk = "io.mockk:mockk-common:$mockkVersion"
    
  • Gradle依赖未同步:即使配置了依赖,若未执行Gradle同步操作,commonTest的classpath中不会包含MockK库,运行时自然找不到相关方法。执行Gradle的Sync Project with Gradle Files操作,或运行./gradlew clean build清理并重新构建项目。
  • 测试类缺少MockK方法导入:IDE可能存在缓存,导致未检测到缺失的导入。在测试类顶部显式导入MockK的核心方法:
    import io.mockk.every
    import io.mockk.mockk
    import io.mockk.verify
    
    或使用通配符导入所有MockK方法:import io.mockk.*。
  • MockK版本与Kotlin版本不兼容:你使用的MockK 1.12.5是较旧的版本,若当前项目的Kotlin版本为1.8及以上,可能存在兼容性问题。建议升级MockK到适配当前Kotlin版本的最新稳定版(如1.13.8或更高)。
  • 依赖范围配置问题:虽然在commonTest中使用implementation是允许的,但部分场景下testImplementation更符合测试依赖的语义。尝试将implementation(ShareTestDependencies.mockk)改为testImplementation(ShareTestDependencies.mockk),再同步Gradle并重新运行测试。

内容的提问来源于stack exchange,提问作者Sunbey13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 02:15:44