Espresso:从文本视图中获取文本值并存储在字符串中



我想断言我从文本视图中获得的'text'的一部分,然后将其存储在字符串中,但不确定如何做到这一点。

以下是供参考的代码片段:

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"的值存储在一个字符串中,以便以后可以使用它进行断言。

您可能需要创建一个自定义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();

虽然我不建议使用这种方式进行测试断言,但它似乎是非常规的,而且很尴尬。此外,由于withId,您实际上不需要在allOf组合中包含isDescendantOf(...),除非id不是唯一的。

最新更新