I'm trying to refactor an existing UI test into something a little more robust. Basically I have code that looks like this:
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")
However I would like to be able to pass in a MM/DD/YYYY
date and have it dynamically use the spinner.
Aside from creating a large function that:
01
) to (January
)Is there an easier way?
There's probably a better solution, but one way to do this is to simply use DateFormatter
s to convert your passed-in date to strings (provided that the strings in your date picker use the full-length month names and days without leading zeroes):
extension DateFormatter {
static let monthFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MMMM"
return formatter
}()
static let dayFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "d"
return formatter
}()
static let yearFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy"
return formatter
}()
}
extension Date {
var monthDayYearStrings: (month: String, day: String, year: String) {
(DateFormatter.monthFormatter.string(from: self),
DateFormatter.dayFormatter.string(from: self),
DateFormatter.yearFormatter.string(from: self))
}
}
And then use it in your test:
let (month, day, year) = yourPassedInDate.monthDayYearStrings
let datePickers = XCUIApplication().datePickers
datePickers.pickerWheels.element(boundBy: 0).adjust(toPickerWheelValue: month)
datePickers.pickerWheels.element(boundBy: 1).adjust(toPickerWheelValue: day)
datePickers.pickerWheels.element(boundBy: 2).adjust(toPickerWheelValue: year)