Android-тестирование. Как изменить текст TextView с помощью Espresso

Легко обновить EditText с помощью Espresso, но я не могу найти способ изменить текст (например, с помощью метода TextView.setText("someText");) в процессе тестирования.

ViewAction.replaceText(stringToBeSet);

Не работает, потому что это должно быть EditText


person Andrew    schedule 29.09.2015    source источник


Ответы (4)


Вы можете изучить реализацию собственного ViewAction.

Вот модифицированная версия действия replaceText из библиотеки эспрессо, предназначенная для работы с TextView.

 public static ViewAction setTextInTextView(final String value){
            return new ViewAction() {
                @SuppressWarnings("unchecked")
                @Override
                public Matcher<View> getConstraints() {
                    return allOf(isDisplayed(), isAssignableFrom(TextView.class));
                }

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

                @Override
                public String getDescription() {
                    return "replace text";
                }
            };
    }
person Be_Negative    schedule 29.09.2015
comment
Работает как шарм. Понравится еще парочка ваших ответов )) - person Andrew; 29.09.2015
comment
Спасибо, парень, ты помог мне с проблемой typeText. - person emaleavil; 05.01.2016

Kotlin версия отличного ответа @Be_Negative,

Поскольку в Espresso нет ViewAction для установки текста на TextView, вам нужно создать свой собственный.

Шаг 1. Определите новое действие ViewAction для установки текста на TextView, например,

fun setTextInTextView(value: String): ViewAction {
    return object : ViewAction {
        override fun getConstraints(): Matcher<View> {
            return CoreMatchers.allOf(ViewMatchers.isDisplayed(), ViewMatchers.isAssignableFrom(TextView::class.java))
        }

        override fun perform(uiController: UiController, view: View) {
            (view as TextView).text = value
        }

        override fun getDescription(): String {
            return "replace text"
        }
    }
}

А затем используйте его как,

onView(withId(R.id.my_text_view)).perform(setTextInTextView("Espresso is awesome"))
person iCantC    schedule 12.04.2020

Вы можете просто добавить свой макет TextView в объявленный вами макет

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">
        <TextView
            android:textColor="#123456"
            android:textSize="20dp"
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

Напишите код в своем тесте

@RunWith(AndroidJUnit4.class)
public class MainActivityTest {

    @Rule
    public ActivityTestRule<MainActivity> mMain = new ActivityTestRule<> (MainActivity.class);

   /*set text view in 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";
                    }
                };
            }

Теперь ваш метод похож на этот

          //need add your test case here
            @Test
            public void showTextView(){

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

**Теперь вы также можете добавить метод задержки, чтобы показать также эмулятор или реальное устройство*

    /* delay checking of this position */
    private void delay(long i) {

    try {
        Thread.sleep(i);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
person amirul    schedule 06.11.2018

Вы можете просто добавить свой макет TextView в свой макет, который вы объявили

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <TextView
        android:textColor="#123456"
        android:textSize="20dp"
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

** Напишите код в тестовом классе, чтобы проверить, отображается ли текст в текстовом представлении**

 @Test
public void checkUserId(){
    Espresso.onView(withId(R.id.textView)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
}
person Sugandh Kumar    schedule 30.03.2020