【问题标题】:Picking a date with swift UI automation通过 swift UI 自动化选择日期
【发布时间】:2018-01-18 22:26:29
【问题描述】:

在我正在测试的应用程序中有一个 date picker 我正在尝试自动化。轮子默认为明天,我正在尝试将其更改为今天的日期,但距离现在 2 分钟。下面是我用来尝试的代码。

app.pickerWheels.element(boundBy: 0).adjust(toPickerWheelValue: "Today")
app.pickerWheels.element(boundBy: 1).adjust(toPickerWheelValue: "1")
app.pickerWheels.element(boundBy: 2).adjust(toPickerWheelValue: "00")

(在实际代码中,我使用变量而不是硬编码这些字符串)

此代码适用于第二个和第三个轮子(小时和分钟),但对于第一个轮子它不会设置值。测试将失败,并且不会继续超过该点。

我也尝试过传递今天的日期,而不仅仅是“今天”,结果相同。

【问题讨论】:

    标签: swift datepicker automation


    【解决方案1】:

    您可以使用DateFormatter 类和Date 来完成此操作。

        // Initialize the date formatter. Set the timeZone and format. I chose hours and minutes.
        let dateFormatter: DateFormatter = DateFormatter()
        dateFormatter.timeZone =  NSTimeZone.local
        dateFormatter.dateFormat = "HH:mm"
    
        // Initialize the Date instance using a time interval since now.
        let d: Date = Date(timeIntervalSinceNow: 2 * 60)
        print("Current Time = \(dateFormatter.string(from: Date())), Two-Minutes-From-Now = \(dateFormatter.string(from: d))")
    

    输出: Current Time = 23:57, Two-Minutes-From-Now = 23:59

    Date 存储为自 1970 年 1 月 1 日以来的时间间隔。您可以通过添加或减去秒来操作日期。在这里,我在当前时间间隔中添加了2 * 60 或两个 60 秒分钟(以双精度表示的大值)。这指向未来的两分钟。

    现在,如果您在没有格式化程序的情况下打印日期,它将只显示当前时间,而不考虑您的时区。因此,如果您希望它与您的时区准确,您需要先在格式化程序中进行设置。请注意,它不会改变时间,只是它对您的表示。

    【讨论】:

    • 感谢您提供的信息,但是在我已经使用 Date 和 DateFormatter 获得了日期和时间信息之后,我的问题就存在了。也许我的问题不够清楚,但是当我使用app.pickerWheels.element(boundBy: 0).adjust(toPickerWheelValue: "Today") 时,它不会将选择轮移动到今天的值。我已经尝试以相同的格式(E MMM d)向它传递一个带有日期的字符串,但同样的问题仍然存在,它未能通过测试。
    • @ZacharyHuffman 好的,我稍后再看。谢谢你的解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 2011-01-30
    • 2011-10-16
    • 1970-01-01
    • 2010-09-19
    • 2013-08-02
    相关资源
    最近更新 更多