4

I have a MaterialDatePicker dialog, and I want to write an Espresso test that selects a date. Unfortunately, I can't use PickerActions for this. I'm looking for something similar to this:

onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(year, monthOfYear, dayOfMonth));

Does anyone have any ideas on how to go about this?

Thanks in advance!

nullbyte
  • 1,178
  • 8
  • 16
  • 1
    Does this answer your question? [How to set time to MaterialDateTimePicker with Espresso](https://stackoverflow.com/questions/34658871/how-to-set-time-to-materialdatetimepicker-with-espresso) – agoff Jul 29 '21 at 16:32
  • No, it's a different Android component, and they work quite differently. – nullbyte Jul 30 '21 at 03:37

1 Answers1

1

I found this answer buried in the question linked above, which you may find useful for setting the date when the InputMode is INPUT_MODE_TEXT.

public static void setDate(LocalDate date){
    onView(withTagValue((Matchers.is((Object) ("TOGGLE_BUTTON_TAG"))))).perform(click());
    onView(withId(com.google.android.material.R.id.mtrl_picker_text_input_date)).perform(replaceText(date.format(DateTimeFormatter.ofPattern("M/d/yy"))));
}

public static void setTime(LocalTime time){
    onView(withId(com.google.android.material.R.id.material_timepicker_mode_button)).perform(click());
    onView(withId(com.google.android.material.R.id.material_hour_text_input)).perform(click());
    onView(allOf(isDisplayed(), withClassName(is(AppCompatEditText.class.getName())))).perform(replaceText(time.format(DateTimeFormatter.ofPattern("hh"))));
    onView(withId(com.google.android.material.R.id.material_minute_text_input)).perform(click());
    onView(allOf(isDisplayed(), withClassName(is(AppCompatEditText.class.getName())))).perform(replaceText(time.format(DateTimeFormatter.ofPattern("mm"))));
}

It's definitely janky in terms of relying very closely on the ids to not change, but it is effective.

If you want to select a date when the InputMode is INPUT_MODE_CALENDAR, then this worked for me:

onView(
   // the date you are selecting must be visible for this to work 
   withContentDescription("Mon, Jan 1, 1990")
).inRoot(RootMatchers.isDialog())
  .perform(click())

onView(withId(com.google.android.material.R.id.confirm_button))
  .perform(click())

You could expand this answer further to select a different month/day/year by clicking on the appropriate buttons in the Material Date Picker layout. You can go spelunking for the ids in the source code.

Chantell Osejo
  • 1,456
  • 15
  • 25