如何使用 espresso 从 textview 获取文本 [英] how to get text from textview using espresso

查看:26
本文介绍了如何使用 espresso 从 textview 获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要在 LinearLayout 的文本视图中显示文本字符串.浓缩咖啡能做到吗?如果没有,是否有其他方法可以做到这一点,或者我可以在 espresso 测试用例中使用 android api 吗?我正在使用 API 17 18 或更新的 espresso 1.1(它应该是最新的.).我对此一无所知.谢谢.

I want get text string shown in a textview in LinearLayout. can espresso do that? If not, is there other way to do that or can I use android api in espresso test case? I am using API 17 18 or newer, espresso 1.1(It should be the latest one.). I have no clue about this. Thanks.

推荐答案

基本思想是使用具有内部 ViewAction 的方法,该方法在其 perform 方法中检索文本.匿名类只能访问final字段,所以我们不能让它设置一个getText()的局部变量,而是使用一个String数组从ViewAction<中取出字符串/代码>.

The basic idea is to use a method with an internal ViewAction that retrieves the text in its perform method. Anonymous classes can only access final fields, so we cannot just let it set a local variable of getText(), but instead an array of String is used to get the string out of the ViewAction.

    String getText(final Matcher<View> matcher) {
        final String[] stringHolder = { null };
        onView(matcher).perform(new ViewAction() {
            @Override
            public Matcher<View> getConstraints() {
                return isAssignableFrom(TextView.class);
            }
    
            @Override
            public String getDescription() {
                return "getting text from a TextView";
            }
    
            @Override
            public void perform(UiController uiController, View view) {
                TextView tv = (TextView)view; //Save, because of check in getConstraints()
                stringHolder[0] = tv.getText().toString();
            }
        });
        return stringHolder[0];
    }

注意:应谨慎使用此类视图数据检索器.如果你经常发现自己在编写这种方法,那么很有可能你从一开始就做错了什么.也永远不要访问 ViewAssertionViewAction 之外的视图,因为只有在那里才能确保交互是安全的,因为它是从 UI 线程运行的,并在执行之前检查它是否没有其他交互干预.

Note: This kind of view data retrievers should be used with care. If you are constantly finding yourself writing this kind of methods, there is a good chance, you're doing something wrong from the get go. Also don't ever access the View outside of a ViewAssertion or ViewAction, because only there it is made sure, that interaction is safe, as it is run from UI thread, and before execution it is checked, that no other interactions meddle.

这篇关于如何使用 espresso 从 textview 获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆