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

KMM跨模块问题:如何从模块2访问模块1的commonTest类

KMM模块间复用commonTest测试类的可行方案

这个需求完全可行,你之前配置失败是因为Gradle默认不会将模块的测试源集(如commonTest)暴露给其他模块,需要通过显式配置让测试代码成为可被依赖的构件。以下是两种可靠的实现方式:

方式一:直接暴露模块1的commonTest输出

适用于需要复用模块1commonTest中所有测试类的场景:

  1. 在模块1的build.gradle.kts中配置测试构件
    添加自定义配置,将commonTest的代码输出打包为可依赖的构件:

    kotlin {
        sourceSets {
            val commonTest by getting {
                dependencies {
                    implementation(kotlin("test"))
                    // 模块1自身的commonTest依赖
                }
            }
        }
    
        // 创建可被其他模块依赖的测试配置
        configurations.create("commonTestElements") {
            extendsFrom(configurations["commonTestImplementation"])
            outgoing.artifact(commonTest.output)
        }
    }
    
  2. 在模块2的build.gradle.kts中添加依赖
    直接依赖模块1的commonTestElements配置:

    kotlin {
        sourceSets {
            val commonTest by getting {
                dependencies {
                    implementation(project(":module1", "commonTestElements"))
                }
            }
        }
    }
    

方式二:使用Gradle Test Fixtures插件(更规范)

如果只是需要复用模块1中的测试工具类、基类等,而非全部测试用例,推荐用这种方式,它能更好地分离可复用测试代码与模块自身的测试代码:

  1. 模块1中配置Test Fixtures
    首先应用插件,然后定义测试fixtures的源集,并将可复用的测试代码移到src/testFixtures/common/kotlin/目录下:

    plugins {
        id("com.android.library")
        kotlin("multiplatform")
        id("java-test-fixtures") // 启用Test Fixtures插件
    }
    
    kotlin {
        sourceSets {
            val commonTest by getting {
                dependencies {
                    implementation(kotlin("test"))
                    // 模块1自身测试可以依赖fixtures
                    implementation(testFixtures(project))
                }
            }
            // 定义测试fixtures的common源集
            val testFixturesCommon by creating {
                dependsOn(commonMain)
            }
        }
    }
    
  2. 模块2中依赖Test Fixtures
    在模块2的commonTest中添加对模块1测试fixtures的依赖:

    kotlin {
        sourceSets {
            val commonTest by getting {
                dependencies {
                    implementation(testFixtures(project(":module1")))
                }
            }
        }
    }
    

配置完成后,同步Gradle,模块2的commonTest就能正常复用模块1的测试类或工具类了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 16:25:19