KMM库commonMain中无法解析kotlin.test.Test的原因排查
问题描述
我想要创建一个名为MyTestLib的KMM测试库,该库提供测试接口供主业务应用项目调用,但在commonMain模块中引入kotlin.test.Test时出现无法解析的问题。执行./gradlew test后,报错提示kotlin.test.Test无法解析。相关配置及代码如下:
build.kts配置
plugins { kotlin("multiplatform") version "1.7.21" } group = "com.xingpeds" version = "1.0-SNAPSHOT" repositories { mavenCentral() } kotlin { jvm { compilations.all { kotlinOptions.jvmTarget = "1.8" } withJava() testRuns["test"].executionTask.configure { useJUnitPlatform() } } js(BOTH) { browser { commonWebpackConfig { cssSupport.enabled = true } } } 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.") } sourceSets { val commonMain by getting { dependencies { implementation(kotlin("test")) } } val commonTest by getting { dependencies { implementation(kotlin("test")) } } val jvmMain by getting val jvmTest by getting val jsMain by getting val jsTest by getting val nativeMain by getting val nativeTest by getting } }
commonMain测试接口代码
import kotlin.test.Test import kotlin.test.fail interface TestTemplate { @Test fun firstTemplate() { fail("red stage") } }
JVM测试类代码
class ConcreteTest : TestTemplate
原因分析及解决办法
核心原因
kotlin("test")是测试运行时专用依赖,仅为test源码集(如commonTest、jvmTest)提供测试执行的实现逻辑,默认不会在main源码集(如commonMain、jvmMain)中暴露kotlin.test的API(包括@Test注解)。你将其配置在commonMain的implementation依赖中,导致主源码路径下无法加载到kotlin.test.Test的定义,从而触发解析错误。
kotlin.test的注解(如@Test)实际定义在kotlin-test-common模块中,这个模块专门用于在主源码集里提供测试相关的接口定义,供跨平台测试逻辑复用。
解决步骤
- 修改
commonMain的依赖配置,将implementation(kotlin("test"))替换为api(kotlin("test-common")),这样主源码集可以访问kotlin.test的注解接口,同时依赖该库的外部项目也能继承此依赖,在自身测试代码中使用TestTemplate接口:val commonMain by getting { dependencies { api(kotlin("test-common")) } } - 保留
commonTest中的implementation(kotlin("test"))配置,确保测试运行时拥有对应的执行实现,不影响测试用例的运行。
修改完成后重新执行./gradlew test即可解决无法解析的问题。
内容的提问来源于stack exchange,提问作者Kyle M
相关产品推荐
相关产品推荐

