如何在Android中使用Espresso为Textview设置值 [英] How to set a value to the textview using Espresso in Android

查看:101
本文介绍了如何在Android中使用Espresso为Textview设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Fragment编写测试用例.我可以将文本设置为Edittext,但无法通过测试将setText设置为文本视图.请任何人帮助我解决此问题.以下是我用于编辑文本的代码.

I am writing the test cases for the Fragment. I can able to set a text to the Edittext but am unable to setText to the text view from testing. Please, anyone, help me to resolve this issue.Bellow is my code for edit text.

   onView(withId(R.id.editText))
        .perform(typeText("my text"), closeSoftKeyboard());

请帮助我如何在文本视图中设置文本.

Please help me how to set a text to the text view.

推荐答案

由于

查看先决条件:

View preconditions:

必须在屏幕上显示

必须支持输入法

输入法 >(用户无法通过键盘或其他方式在其中输入值),因此出现了问题

Input method is not supported by TextView(user cannot input values into it via keyboard or something else) so hence the issue

解决方案:您可以实现自己的视图ViewAction

Solution : you can implement your own view ViewAction

如何创建View操作以在TextView上设置文本

public static ViewAction setTextInTextView(final String value){
            return new ViewAction() {
                @SuppressWarnings("unchecked")
                @Override
                public Matcher<View> getConstraints() {
                    return allOf(isDisplayed(), isAssignableFrom(TextView.class));
//                                            ^^^^^^^^^^^^^^^^^^^ 
// To check that the found view is TextView or it's subclass like EditText
// so it will work for TextView and it's descendants  
                }

                @Override
                public void perform(UiController uiController, View view) {
                    ((TextView) view).setText(value);
                }

                @Override
                public String getDescription() {
                    return "replace text";
                }
            };
    }

那你就可以做

onView(withId(R.id.editText))
        .perform(setTextInTextView("my text"));

这篇关于如何在Android中使用Espresso为Textview设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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