Android Espresso-根据参考资料中的字符串断言屏幕上的文本

Android Espresso-根据参考资料中的字符串断言屏幕上的文本,android,android-espresso,Android,Android Espresso,我在strings.xml资源文件中有以下文本: <string name="txt_to_assert">My Text</string> 目前,我正试图在用浓缩咖啡编写的UI测试中使用这个字符串资源。我正在考虑这样做: String myTextFromResources = getString(R.string.main_ent_mil_new_mileage); onView(allOf(withId(R.id.my_text_on_screen), withT

我在strings.xml资源文件中有以下文本:

<string name="txt_to_assert">My Text</string>
目前,我正试图在用浓缩咖啡编写的UI测试中使用这个字符串资源。我正在考虑这样做:

String myTextFromResources = getString(R.string.main_ent_mil_new_mileage);
onView(allOf(withId(R.id.my_text_on_screen), withText(myTextFromResources))
    .check(matches(isDisplayed()));
但是,
getString(…)
方法不能在此处使用。
有没有办法从strings.xml资源文件中获取文本,并在用Espresso编写的测试中使用它?

使用此函数:

private String getResourceString(int id) {
    Context targetContext = InstrumentationRegistry.getTargetContext();
    return targetContext.getResources().getString(id);
}
您只需使用字符串的id调用它并执行操作:

String myTextFromResources = getResourceString(R.string.main_ent_mil_new_mileage);
onView(allOf(withId(R.id.my_text_on_screen), withText(myTextFromResources))
    .check(matches(isDisplayed()));
*为新的浓缩咖啡版本编辑:

var resources: Resources = InstrumentationRegistry.getInstrumentation().targetContext.resources
使用新版本的Espresso,您应该能够使用ViewMatcher直接调用字符串资源。因此,首先,我建议直接尝试此导入

import static android.support.test.espresso.matcher.ViewMatchers.withText;
然后在代码中:

withText(R.string.my_string_resource)

如果您必须在字符串资源之前附加一个文本,那么您必须这样做

val text=getApplicationContext<Context().getResources().getString(R.string.title_tenth_char) 

val text=getApplicationContextKotlin:

var resources: Resources = InstrumentationRegistry.getInstrumentation().targetContext.resources

androidx.test.platform.app.InstrumentationRegistry
不推荐使用
androidx.test.core.app.ApplicationProvider

val targetContext: Context = ApplicationProvider.getApplicationContext()
val test: String =  targetContext.getResources().getString(R.string. my_text_on_screen)

很高兴读到这个!你可以接受我的回答,或者投票支持我,伙计;)投票通过,但我收到的消息是,声誉低于15的用户的投票被考虑在内,但没有公开显示。如果我们想使用hamcrest的equalToIgnoringCase,您的第一种方法仍然有效。示例:onView(allOf(带文本(equalToIgnoringCase(getResourceString(R.string.promos\u activity\u tab\u store)))完全显示()).perform(单击());我得到一个错误:Resources$NotFoundException:字符串资源ID