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

问题描述 投票:0回答:2

我正在尝试实现一个 UI 测试,调整样本选择器滚轮的选定值,如下所示:

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($0)
        }
      }
      .accessibility(identifier: "picker")
      Text("You selected: \(selectedColor)")
    }
  }
}

UI测试

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

但是,当使用函数 adjustment(toPickerWheelValue: ) 时,滚轮只会按照所需值的方向移动到列表中的下一项。在上面的 UI 测试示例中,结果是轮子移至“绿色”。如果我再次调用该函数,滚轮将移动一步以选择“蓝色”,依此类推。为什么会出现这种情况?

使用:Xcode 12.4 和 iOS 14.4

ios swift swiftui xctest picker
2个回答
7
投票

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)

0
投票

如果您的选择器是内联样式的(默认情况下),则选择器及其内容将在辅助功能层次结构中显示为“按钮”。我已在 Xcode 16.1 上完成此步骤以成功选择一个选项。

func testPickerSelection() throws {
    let button = app.buttons["picker"]
    let buttonExists = button.waitForExistence(timeout: 1)
    if buttonExists {
        button.tap()
        let purpleOption = app.buttons["Purple"]
        XCTAssertTrue(purpleOption.exists, "Purple option is not visible.")
        purpleOption.tap()
        XCTAssertEqual(button.label, "Choose a color, Purple", "Picker did not update correctly.")
    } else {
        XCTFail("Button can't be found.")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.