Lassie
Lassie

Reputation: 994

How to set visibility of the textview using android espresso test

I want to set visibility for the text view from test cases.I am using espresso for testing the UI. I used the viewAction to set the text to the text view. But I want to set visibility for the text view. Please, any one helps me to resolve this issue. Here is my code for setting the text to the text view.

public ViewAction setTextInTextView(final String value){
    return new ViewAction() {
        @SuppressWarnings("unchecked")
        @Override
        public void perform(UiController uiController, View view) {
            ((TextView) view).setText(value);
        }

        @Override
        public Matcher<View> getConstraints() {
            return allOf(isDisplayed(), isAssignableFrom(TextView.class));
        }

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

Upvotes: 5

Views: 3687

Answers (1)

Neerajlal K
Neerajlal K

Reputation: 6828

Try this,

public class MainActivityInstrumentationTest {

    @Rule
    public ActivityTestRule<MainActivity> activityTestRule = new ActivityTestRule<>(MainActivity.class);

    @Test
    public void validateEditText() {

        onView(withId(R.id.out)).perform(setTextViewVisibitity(true));

        // Just for viewing the results. Remove after use.
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        onView(withId(R.id.out)).perform(setTextViewVisibitity(false));

        // Just for viewing the results. Remove after use.
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static ViewAction setTextViewVisibitity(final boolean value) {
        return new ViewAction() {

            @Override
            public Matcher<View> getConstraints() {
                return isAssignableFrom(TextView.class);
            }

            @Override
            public void perform(UiController uiController, View view) {
                view.setVisibility(value ? View.VISIBLE : View.GONE);
            }

            @Override
            public String getDescription() {
                return "Show / Hide View";
            }
        };
    }
}

Upvotes: 9

Related Questions