使用InstrumentationRegistry.getContext().getString()时,为什么会得到Resources $ NotFoundException?

roo*_*roo 6 resources instrumentation android android-studio

我正在运行Android Instrumentation测试,当我使用Contextreturn by InstrumentationRegistry.getContext()检索给定id的字符串时,我收到消息:

android.content.res.Resources$NotFoundException: String resource ID #0x7f060020

我从其他字符串资源尝试过ID,但无济于事.

我在stackoverflow上查看了有关同一个异常的几个问题,但所有这些都涉及将字符串id传递给View.setText.这对我来说无关紧要,因为我正在创建一个库而且根本没有View.

小智 9

您可以像在此示例中一样使用targetContext:

InstrumentationRegistry.getTargetContext().getString(R.id.name);
Run Code Online (Sandbox Code Playgroud)

这应该获取你的字符串资源


roo*_*roo -1

我自己想出了这个办法。正在测试的模块被设置为应用程序项目,但它应该被设置为库项目。在模块的build.gradle文件中我改变了这一点:

apply plugin: 'com.android.application'

对此:

apply plugin: 'com.android.library'

我还必须applicationIdbuild.gradle文件中删除该行,因为它不适用于图书馆项目。

一旦我进行了这些更改,就可以找到字符串的资源 ID。