Espresso读取字符串文件值

时间:2016-07-25 09:48:29

标签: android android-espresso

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

我在androidTest下保留res文件夹,并且能够同步并生成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"

有什么方法可以保留并在我的项目测试模块中使用String资源,它不会添加到我的生产版本中。

2 个答案:

答案 0 :(得分:13)

您应该使用InstrumentationRegistry.getContext()代替InstrumentationRegistry.getTargetContext(),然后对生成的R文件使用适当的包(默认情况下会将.test附加到您的包中):

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

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

答案 1 :(得分:1)

在2019年,我们应该做(科特琳)。

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

val description = resources.getString(DESCRIPTION)