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

Kotlin多平台:如何访问子模块commonTest中的测试类?

解决Kotlin多平台项目中子模块测试类跨模块访问问题

问题本质:你当前仅在shared模块的commonMain源码集中依赖了base模块的主源码,但BaseTest属于base模块的commonTest源码集,主依赖不会自动传递测试源码集的内容,因此shared模块的commonTest无法找到该类。

解决方案

方案一:直接依赖子模块的测试源码集(本地多模块场景)

修改shared模块的Gradle配置,在commonTest的依赖中明确添加对base模块测试源码集的依赖:

plugins {
    kotlin("multiplatform")
    kotlin("native.cocoapods")
    id("com.android.library")
}

version = "1.0"

kotlin {
    android()
    iosX64()

    sourceSets {
        val commonMain by getting {
            dependencies {
                implementation(project(":base"))
            }
        }
        val commonTest by getting {
            dependsOn(commonMain)
            dependencies {
                implementation(kotlin("test"))
                // 新增:依赖base模块的commonTest源码集
                testImplementation(project(":base", "commonTestElements"))
            }
        }
        val androidMain by getting
        val androidTest by getting
        val iosMain by creating {
            dependsOn(commonMain)
        }
        val iosTest by creating {
            dependsOn(commonTest)
        }
    }
}

android {
    compileSdk = 32
    sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
    defaultConfig {
        minSdk = 26
        targetSdk = 32
    }
}

方案二:使用Test Fixtures(规范共享场景)

这是Kotlin官方推荐的测试代码共享方式,适合需要将测试工具类复用给多个模块或发布模块的场景:

  1. 配置base模块:启用test fixtures插件,并将测试共享类移至testFixtures/commonMain源码集(或让test fixtures依赖现有commonTest)
plugins {
    kotlin("multiplatform")
    id("com.android.library")
    // 启用test fixtures插件
    `kotlin-test-fixtures`
}

kotlin {
    // 其他配置...
    sourceSets {
        // 可选:让test fixtures依赖commonTest源码集,复用现有测试类
        val testFixturesCommonMain by getting {
            dependsOn(commonTest)
        }
    }
}
  1. 配置shared模块:在commonTest中依赖base模块的test fixtures
val commonTest by getting {
    dependsOn(commonMain)
    dependencies {
        implementation(kotlin("test"))
        // 依赖base模块的test fixtures
        testFixturesImplementation(project(":base"))
    }
}

验证修改

修改后,测试代码即可正常导入并使用BaseTest:

package com.example.myapplication

import com.example.base.Base
import com.example.base.BaseTest
import kotlin.test.Test

class Test {
    @Test
    fun test() {
        Base()
        BaseTest()
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:55:17