Espresso 读取字符串文件值

Espresso Read String File Value

我想在我的 androidTest 模块中保留一个 Sting 和 Raw 文件,并在 Espresso 测试中需要时读取它。

我将 res 文件夹保存在 androidTest 下,并且能够同步并为其生成 R 文件。但是当我尝试使用

访问字符串资源时

getTargetContext.getString(R.string.product_name) 或使用 mAcitivityRule.getActivity.getString(R.string.product_name) 我得到了一些随机值,它甚至没有在资源文件中的任何地方使用过。

String output: "res/drawable-v21/abc_action_bar_item_background_material.xml"

有什么方法可以在我的项目测试模块中保留和使用字符串资源,并且它不会添加到我的生产构建中。

您应该使用 InstrumentationRegistry.getContext() 而不是 InstrumentationRegistry.getTargetContext(),然后为生成的 R 文件使用适当的包(默认情况下它将附加 .test 到您的包):

Resources resources = InstrumentationRegistry.getContext().getResources();
String name = resources.getString(com.your_package.test.R.string.product_name);

注意资源名称中的test部分。

2019年我们应该做的(Kotlin)

val resources = ApplicationProvider.getApplicationContext<App>().resources

val description = resources.getString(DESCRIPTION)