Android testing. Espresso. Change text in a TextView

前端 未结 4 1584
南方客
南方客 2020-12-10 16:01

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.

4条回答
  •  Happy的楠姐
    2020-12-10 16:13

    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 {
                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"))
    

提交回复
热议问题