在我的测试中,
我检查我登陆的每个页面的标题中的文字。
我可以将文本与“登录”(例如R.id.toolbar_text
)匹配,看看它是通过还是失败。但是,我想知道它是否失败,我在R.id.toolbar_text
对象中的文本是什么。
Espresso Android中有getText()
选项吗?
如何从ID中提取'文字?
答案 0 :(得分:1)
试试这个(kotlin例子):
val toolbar: ViewInteraction = onView(withId(R.id.toolbar_text))
fun getText(viewInteraction: ViewInteraction): String? {
val stringHolder = arrayOf<String?>(null)
viewInteraction.perform(object : ViewAction {
override fun getConstraints() = isAssignableFrom(TextView::class.java)
override fun getDescription() = "Get text from View: ${stringHolder[0]}"
override fun perform(uiController: UiController, view: View) {
val tv = view as TextView
stringHolder[0] = tv.text.toString()
}
})
return stringHolder[0]
}
val text = getText(toolbar)
答案 1 :(得分:1)
以下是Java中getText()的等效实现:
public static String getText(final Matcher<View> matcher) {
try {
final String[] stringHolder = {null};
onView(matcher).perform(new ViewAction() {
@Override
public Matcher<View> getConstraints() {
return isAssignableFrom(TextView.class);
}
@Override
public String getDescription() {
return "get text";
}
@Override
public void perform(UiController uiController, View view) {
TextView tv = (TextView) view;
stringHolder[0] = tv.getText().toString();
}
});
if (stringHolder[0] == null || stringHolder[0] == "") {
fail("no text found");
}
return stringHolder[0];
} catch (Exception e) {
fail("null found");
return null;
}
}