浓缩咖啡:从textview获取文本值并存储在String中?

时间:2018-11-12 19:35:59

标签: java android-espresso

我想断言从textview中获取的“文本”的一部分,然后将其存储在字符串中,但是不确定我将如何执行此操作。

以下是参考代码段:

private void validateFlightOverviewWidgetDate(int resId, String value, boolean outBound) throws Throwable {
    if (ProductFlavorFeatureConfiguration.getInstance().getDefaultPOS() == PointOfSaleId.UNITED_STATES) {
        onView(allOf(outBound ? isDescendantOfA(withId(R.id.package_outbound_flight_widget))
                : isDescendantOfA(withId(R.id.package_inbound_flight_widget)),
            withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE),
            withId(resId)))
            .check(matches(withText(containsString("Dec 22 "))));

我想将“ Dec 22”的值存储在字符串中,以便以后可以将其用于断言。

1 个答案:

答案 0 :(得分:0)

您可能必须创建一个自定义ViewAction来帮助您从TextView中获取文本:

public class GetTextAction implements ViewAction {

    private CharSequence text;

    @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 textView = (TextView) view;
        text = textView.getText();
    }

    @Nullable
    public CharSequence getText() {
        return text;
    }
}

然后您可以通过以下方式获取文字

GetTextAction action = new GetTextAction();
onView(allOf(isDescendantOf(...), withId(...), withEffectiveVisibility(...)))
    .perform(action);

CharSequence text = action.getText();

尽管我不建议将这种方式用于测试断言,但它似乎不合常规且笨拙。另外,除非{id}不是唯一的,否则isDescendantOf(...)确实不需要allOf内的withId组合中的ifelse()