Pranit Pranit - 2 months ago 14
Android Question

Automating number picker in android using espresso

How to automate number picker using espresso. I want to set specific time in the timePicker using espresso.

Answer

To match a View by its class name you can simply use:

 onView(withClassName(Matchers.equalTo(TimePicker.class.getName())));

Once you have the ViewInteraction object you can set a value on it defining and using a ViewAction as following:

public static ViewAction setTime(int hour, int minute) {
        return new ViewAction() {
            @Override
            public void perform(UiController uiController, View view) {
                TimePicker tp = (TimePicker) view;
                tp.setCurrentHour(hour);
                tp.setCurrentMinute(minute)
            }
            @Override
            public String getDescription() {
                return "Set the passed time into the TimePicker";
            }
            @Override
            public Matcher<View> getConstraints() {
                return ViewMatchers.isAssignableFrom(TimePicker.class);
            }
        };
    }