You need to enable JavaScript to run this app. Espresso测试访问androidTest资源出现Resources$NotFoundException如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Espresso测试访问androidTest资源出现Resources$NotFoundException如何解决

错误根因

你使用的InstrumentationRegistry.getInstrumentation().targetContext是被测主应用的上下文,仅能访问主工程src/main/res目录下的资源。你存放在androidTest/res下的资源会被打包到独立的测试APK中,不属于主应用的资源索引,因此用主应用上下文读取测试包的资源ID会抛出找不到资源的异常。

解决方案

将targetContext替换为测试APK自身的上下文context即可:

@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
    @Test
    fun test() {
        // 改为使用测试APK的context
        val result = InstrumentationRegistry.getInstrumentation().context.getString(
            com.myproject.test.R.string.my_test
        )
        assertEquals("my test", result)
    }
}

仍报错的排查项

  • 确认strings.xml存放路径为src/androidTest/res/values/,不要错放到主工程或单元测试的test目录下
  • 确认引用的R类是测试包的com.myproject.test.R,不要误引用主工程的R类
  • 清理项目构建缓存后重新编译运行,避免旧的资源索引残留导致异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 19:21:01