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
TextView tv1 = (TextView)findViewById(R. id. textView1); tv1. setText("Hello"); setContentView(tv1);
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 .
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With