简体   繁体   中英

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";
        }
    };
} 

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";
            }
        };
    }
}

Can you tell me why You want set visibility by ui test? Ui test should work like user so it shouldn't set visibiliti programaticaly. If you want let user to show/hide textview you should prepare another interaction view (like button) which react for axample on click and perform method which setVisibility for your textView. When you do this you can use additional view to seting visibility by esspresso. You can add invisible button (with background color)for it too :).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM