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

多模块项目中ModuleB仪器化测试无法读取ModuleA资源怎么办?

解决方案:跨模块Compose仪器化测试资源找不到问题
  • 确认资源存放目录:保证ModuleA中报错的资源位于src/main/res下,不能放在src/test/res或src/androidTest/res——测试目录的资源仅对当前模块的测试可见,无法被其他模块的测试引用。

  • 修正依赖配置:将ModuleB中针对ModuleA的androidTest依赖改为变体感知配置,确保测试构建能获取到ModuleA的debug资源:

    // Groovy语法
    androidTestImplementation project(path: ':moduleA', configuration: 'debug')
    
    // Kotlin DSL语法
    androidTestImplementation(project(path = ":moduleA", configuration = "debug"))
    

    若使用AGP 7.0+版本,也可通过变体匹配自动处理,让ModuleB的debug测试变体默认依赖ModuleA的debug变体。

  • 清理构建缓存:执行以下命令清理缓存后重新构建测试,避免旧缓存导致资源未正确打包:

    ./gradlew clean
    ./gradlew moduleB:connectedAndroidTest
    
  • 检查测试上下文:在Compose仪器化测试中,确保使用的上下文能访问跨模块资源。如果是单独测试Compose组件,可通过createComposeRule()启动空Activity,或使用Application上下文作为资源上下文:

    @Test
    fun testComposeComponent() {
        composeRule.setContent {
            val context = ApplicationProvider.getApplicationContext<Context>()
            Text(text = context.getString(R.string.your_string_resource_from_moduleA))
        }
    }
    
  • 排查ModuleA构建配置:确认ModuleA的build.gradle/build.gradle.kts中没有错误的资源排除规则,比如:

    android {
        sourceSets {
            main {
                // 确保未排除res目录
                res.srcDirs("src/main/res")
            }
        }
    }
    

内容的提问来源于stack exchange,提问作者Ángel Gómez García

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:13:16