简体   繁体   English

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

[英]Espresso: Getting a text value from a textview and storing in a String?

I wanted to assert a part of the 'text' i get from a textview and later store it in a string, but not sure how i am going to do this. 我想断言我从textview中获取的“文本”的一部分,然后将其存储在字符串中,但不确定我将如何执行此操作。

Following is the code snippet for reference : 以下是供参考的代码段:

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 "))));

I want to store the value of "Dec 22" in a string so that later i can use it for assertion. 我想将“ Dec 22”的值存储在字符串中,以便以后可以将其用于断言。

You may have to create a custom ViewAction to help you to get text from TextView : 您可能需要创建一个自定义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;
    }
}

Then you can get text by: 然后,您可以通过以下方式获取文字:

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

CharSequence text = action.getText();

Though I'd not recommend to use this way for test assertion, it seems unconventional and awkward . 尽管我不建议将这种方式用于测试断言,但它看起来不合常规且笨拙 Also, you don't really need to have isDescendantOf(...) in your allOf combination because of withId , unless the id is not unique. 此外,除非有id唯一,否则由于withId ,实际上不需要在allOf组合中包含isDescendantOf(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM