iOS UI 测试动态日期选择器

iOS UI Test Dynamic Datepicker

我正在尝试将现有的 UI 测试重构为更可靠的测试。基本上我的代码看起来像这样:

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")

但是我希望能够传入一个 MM/DD/YYYY 日期并让它动态地使用微调器。

除了创建一个大型函数之外:

  1. 将 01/01/2020 解析为 3 个整数
  2. 将第一个 int 转换为字符串 (01) 到 (January)

有没有更简单的方法?

可能有更好的解决方案,但一种方法是简单地使用 DateFormatters 将您传入的日期转换为字符串(前提是您的日期选择器中的字符串使用全长不带前导零的月份名称和日期):

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))
    }
}

然后在你的测试中使用它:

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)