Use espresso with custom EditText

Issue

Here is part of my layout:

<com.rey.material.widget.EditText
            android:id"@+id/tagEditorSettings"
            android:layout_width"match_parent"
            android:layout_height"48dp"
            android:layout_marginStart"10dp"
            android:layout_toEndOf"@+id/circularProgressbar"
            android:hint"@string/tag_name_tag_settings"
            android:inputType"text"
            android:textSize"18sp"
            app:et_dividerColor"@color/my_primary"
            app:et_dividerHeight"1dp"
            app:et_inputId"@+id/name_input"
            app:et_labelEnable"true"
            app:et_labelTextSize"14sp"
            app:et_supportLines"1" />

and my testing code:

onView(withId(R.id.tagEditorSettings))
                .perform(click()).perform(clearText());

And when I try to run it I get such error:

Caused by: java.lang.RuntimeException: Action will not be performed because the target view does not match one or more of the following constraints: (is displayed on the screen to the user and is assignable from class: class android.widget.EditText)

As I understand the problem is with “is assignable from class: class android.widget.EditText”, but could someone please advice, how I can fix it and use in my case?

Solution

Issue: com.rey.material.widget.EditText is extended from Framelayout and clearText uses ReplaceTextAction as

  public static ViewAction clearText() {
      return actionWithAssertions(new ReplaceTextAction(""));
  }

where ReplaceTextAction enforces the view, a type of EditText as

allOf(isDisplayed(), isAssignableFrom(EditText.class));
//                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Since rey...EdiText is not a subclass of EditText hence the error


Solution : create your own ViewAction as

public static ViewAction clearTextInCustomView(){
            return new ViewAction() {
                @SuppressWarnings("unchecked")
                @Override
                public Matcher<View> getConstraints() {
                    return allOf(isDisplayed(), isAssignableFrom(com.rey.material.widget.EditText.class));
//                                            ^^^^^^^^^^^^^^^^^^^ 
// To check that the found view is type of com.rey.material.widget.EditText or it's subclass
                }

                @Override
                public void perform(UiController uiController, View view) {
                    ((com.rey.material.widget.EditText) view).setText("");
                }

                @Override
                public String getDescription() {
                    return "clear text";
                }
            };
    }

And later you can do

onView(withId(R.id.tagEditorSettings))
                .perform(click()).perform(clearTextInCustomView());

Answered By – Pavneet_Singh

Leave a Comment