为什么在使用 InstrumentationRegistry.getContext().getString() 时会出现 Resources$NotFoundException?
Why do I get a Resources$NotFoundException when using InstrumentationRegistry.getContext().getString()?
我是 运行 Android 仪器测试,当我使用 InstrumentationRegistry.getContext()
返回的 Context
来检索给定 id 的字符串时,我收到消息:
android.content.res.Resources$NotFoundException: String resource ID #0x7f060020
我试过其他字符串资源的 ID,但无济于事。
我在 Whosebug 上查看了几个关于这个相同异常的问题,但所有问题都涉及将字符串 id 传递给 View.setText
。这与我无关,因为我正在创建一个库并且根本没有 View
s。
这是我自己想出来的。被测模块被设置为一个应用程序项目,但它应该被设置为一个库项目。在模块的 build.gradle
文件中,我更改了这个:
apply plugin: 'com.android.application'
对此:
apply plugin: 'com.android.library'
我还必须从 build.gradle
文件中删除 applicationId
行,因为它不适用于库项目。
完成这些更改后,可以找到字符串的资源 ID。
您可以像本例中那样使用 targetContext:
InstrumentationRegistry.getTargetContext().getString(R.id.name);
这应该会获取您的字符串资源
我是 运行 Android 仪器测试,当我使用 InstrumentationRegistry.getContext()
返回的 Context
来检索给定 id 的字符串时,我收到消息:
android.content.res.Resources$NotFoundException: String resource ID #0x7f060020
我试过其他字符串资源的 ID,但无济于事。
我在 Whosebug 上查看了几个关于这个相同异常的问题,但所有问题都涉及将字符串 id 传递给 View.setText
。这与我无关,因为我正在创建一个库并且根本没有 View
s。
这是我自己想出来的。被测模块被设置为一个应用程序项目,但它应该被设置为一个库项目。在模块的 build.gradle
文件中,我更改了这个:
apply plugin: 'com.android.application'
对此:
apply plugin: 'com.android.library'
我还必须从 build.gradle
文件中删除 applicationId
行,因为它不适用于库项目。
完成这些更改后,可以找到字符串的资源 ID。
您可以像本例中那样使用 targetContext:
InstrumentationRegistry.getTargetContext().getString(R.id.name);
这应该会获取您的字符串资源