Search code examples
androidtestingtextviewandroid-espressoandroid-testing

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


Solution

  • You can look into implementing your own ViewAction.

    Here is the modified version of the replaceText viewaction from espresso library that is meant to work on the 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";
                    }
                };
        }