Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android testing. How to change text of a TextView using Espresso

It is easy to update an EditText with Espresso, but I can not find a way to change a text (like with a TextView.setText("someText"); method) during the testing process.

ViewAction.replaceText(stringToBeSet);

Is not working, cos it should be an EditText

like image 488
Andrew Avatar asked Sep 29 '15 14:09

Andrew


People also ask

Can we change the text in TextView?

TextView tv1 = (TextView)findViewById(R. id. textView1); tv1. setText("Hello"); setContentView(tv1);

How do I get TextView espresso from text?

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 .


1 Answers

Kotlin version of the @Be_Negative awesome answer,

Since there is no default ViewAction for setting text on TextView in Espresso, you have to create your own.

Step 1: Define a new ViewAction to set text on TextView such as,

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"
        }
    }
}

And then use it as,

onView(withId(R.id.my_text_view)).perform(setTextInTextView("Espresso is awesome"))
like image 182
iCantC Avatar answered Sep 16 '22 17:09

iCantC