kli*_*mos 22 android android-espresso
我在strings.xml资源文件中有以下文本:
<string name="txt_to_assert">My Text</string>
Run Code Online (Sandbox Code Playgroud)
通常在应用程序代码中,要使用此文本并将其显示在屏幕上,我正在执行以下操作:
getString(R.string.main_ent_mil_new_mileage);
Run Code Online (Sandbox Code Playgroud)
目前,我正在尝试在使用Espresso编写的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()));
Run Code Online (Sandbox Code Playgroud)
但是,getString(...)这里不能使用方法.
有没有办法从strings.xml资源文件中获取文本并在使用Espresso编写的测试中使用它?
ada*_*aRi 56
使用此功能:
private String getResourceString(int id) {
Context targetContext = InstrumentationRegistry.getTargetContext();
return targetContext.getResources().getString(id);
}
Run Code Online (Sandbox Code Playgroud)
您只需使用字符串的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()));
Run Code Online (Sandbox Code Playgroud)
*编辑新的Espresso版本:
使用新版Espresso,您应该可以使用ViewMatcher直接调用字符串资源.首先,我建议直接尝试此导入
import static android.support.test.espresso.matcher.ViewMatchers.withText;
Run Code Online (Sandbox Code Playgroud)
然后在代码中:
withText(R.string.my_string_resource)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
科特林:
var resources: Resources = InstrumentationRegistry.getInstrumentation().targetContext.resources
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11947 次 |
| 最近记录: |