我的应用程序使用 SwiftUI Picker,我想测试它是否只包含预期的选择。当我尝试提取 XCTest 中的选项时,我得到一个额外的条目,
Choose an option, Option 1
,即
["Option 1", "Option 2", "Option 3", "Option 4", "Choose an option, Option 1"]
如何仅获得实际/提供的选择?
以下是应用程序代码
struct PickerXCTest: View {
let options = ["Option 1", "Option 2", "Option 3", "Option 4"]
@State private var selectedOption = "Option 1"
var body: some View {
VStack {
let picker = Picker("Choose an option", selection: $selectedOption) {
ForEach(options, id: \.self) {
Text($0)
}
}
picker.pickerStyle(.menu)
.accessibility(identifier: "myPicker")
}
}
} // PickerXCTest()
下面是XCTest代码
func testMenuPicker() throws {
let app = XCUIApplication()
app.launchArguments = ["--appmode", "debug", "--usecase", "stackOverflow", "--subcase", "menuPicker"]
app.launch()
let picker = app/*@START_MENU_TOKEN@*/.buttons["myPicker"]/*[[".buttons[\"Choose an option, Option 1\"]",".buttons[\"myPicker\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/
XCTAssertTrue(picker.waitForExistence(timeout: 5), "Picker did not appear in time")
// Tap the picker to bring up the menu.
picker.tap()
// Access picker items
let pickerItems = app.buttons.allElementsBoundByIndex
// Extract memu choices.
var menuChoices: [String] = []
for item in pickerItems {
menuChoices.append(item.label)
}
//XCTAssertTrue(false, "\(menuChoices)")
} // testMenuPicker()```
我尝试使用与
app.*
相关的不同属性,但我无法想出一种方法来仅返回实际选择。
要返回选择数组,我必须像这样更改您的测试:
选择器角色是
popUpButtons
,而不是buttons
。
访问您一直在测试其存在性的
picker
,而不是新的东西。
选择在
XCUIElement.title
,而不是 .label
func testMenuPicker() throws {
let app = XCUIApplication()
app.launchArguments = ["--appmode", "debug", "--usecase", "stackOverflow", "--subcase", "menuPicker"]
app.launch()
let picker = app.popUpButtons["myPicker"]
XCTAssertTrue(picker.waitForExistence(timeout: 5), "Picker did not appear in time")
// Tap the picker to bring up the menu.
picker.tap()
// Access picker items
let pickerItems = picker.menuItems.allElementsBoundByIndex
// Extract menu choices.
var menuChoices: [String] = []
for item in pickerItems {
menuChoices.append(item.title)
}
XCTAssertEqual(["Option 1", "Option 2", "Option 3", "Option 4"], menuChoices)
}