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
相关产品推荐
相关产品推荐

