8

I'm making a UI Test for an iOS app. I'm having trouble finding out how to use automated testing for a date picker. Right now I'm stuck trying to find the date picker itself so I can change the values.

I've searched many threads regarding this issue but have found nothing.

If anyone has any insight to this it would be much appreciated. Thanks!

Mystified
  • 137
  • 1
  • 9

3 Answers3

23

To get started, I'd advise you to use the "Record UI Test" button in Xcode to easily find out how to access the UIDatePicker in the UI Test.

For a simple UIDatePicker in date mode, changing the date is as simple as:

let datePickers = XCUIApplication().datePickers
datePickers.pickerWheels.element(boundBy: 0).adjust(toPickerWheelValue: "June")
datePickers.pickerWheels.element(boundBy: 1).adjust(toPickerWheelValue: "1")
datePickers.pickerWheels.element(boundBy: 2).adjust(toPickerWheelValue: "2015")

If the datePicker is connected to a UILabel, you could then check if the text in the label has been updated correctly.

b_ray
  • 696
  • 6
  • 10
9

For anyone, supporting multiple localizations, an easier way would be

 let dateComponent = Calendar.current.dateComponents([.day, .month, .year], from: Date())
 let formatter = DateFormatter()
 formatter.dateFormat = "MMMM"
 let monthText = formatter.string(from: Date())

 datePicker.pickerWheels[String(dateComponent.year!)].adjust(toPickerWheelValue: "2017")
 datePicker.pickerWheels[monthText].adjust(toPickerWheelValue: "December")
 datePicker.pickerWheels[String(dateComponent.day!)].adjust(toPickerWheelValue: "21")
Andrew
  • 3,166
  • 21
  • 32
0

In the very end, I gave up, since all solutions are flaky, depending on the device's locale and date. Then I thought by myself: why should I even test this whole UI element? If you need to change date somewhere in your flow, you are better off doing something like this:

  1. Add 2 Buttons, one with a goForward SFSymbol and one with goBackwards.
  2. Add them in your view with the DatePickers, surrounded by #if DEBUG statements
  3. When the user presses one of the buttons, increase/decrease your DatePicker by a predefined static value. That way, you can still test different dates, but no more flaky tests.
J. Doe
  • 12,159
  • 9
  • 60
  • 114