iOS UI 测试在 SwiftUI 应用程序上调整选择器值

iOS UI Test to adjust picker value on SwiftUI app

我正在尝试实施 UI 测试来调整样本选择器轮子的 selected 值,如下所示:

import SwiftUI

struct ContentView: View {

var colors = ["Red", "Green", "Blue", "Yellow", "White", "Black", "Purple", "Cyan"]
@State private var selectedColor = "Red"

  var body: some View {
    VStack {
      Picker("Choose a color", selection: $selectedColor) {
        ForEach(colors, id: \.self) {
          Text([=12=])
        }
      }
      .accessibility(identifier: "picker")
      Text("You selected: \(selectedColor)")
    }
  }
}

UI 测试

let picker = app!.pickers["picker"].pickerWheels.firstMatch
picker.adjust(toPickerWheelValue: "Purple")

但是,当使用函数 adjust(toPickerWheelValue:) 时,滚轮只会按照所需值的方向移动到列表中的下一个项目。在上面的 UI 测试示例中,结果是轮子移动到“绿色”。如果我再次调用该函数,轮子将移动一步到 select "Blue" 等等。为什么会这样?

使用:Xcode 12.4 和 iOS 14.4

adjust(toPickerWheelValue:) 的行为似乎有点违反直觉。您可以编写自己的函数来完成任务:

extension XCUIElement{
    
    func selectPicker(value: String, timeout: TimeInterval) {
        let pickerWheel = pickerWheels.firstMatch
        let row = pickerWheels[value]
        
        while !row.waitForExistence(timeout: timeout) {
            pickerWheel.adjust(toPickerWheelValue: value)
        }
    }
}

然后像这样使用它:

let picker = app.pickers["picker"]
picker.selectPicker(value: "Purple", timeout: 1)