我有一个选择器视图,几个项目:“红色”,“绿色”,“黄色”,“黑色”。在我的UI测试中,我需要从中选择一个特定的项目“绿色”。我正在使用Xcode 7引入的XCTest UI测试API。
到目前为止我设法做的是在单元测试中刷整整个选择器视图。它并不理想,因为它总是将拾取器视图更改为底部项目(向上滑动时)。
let app = XCUIApplication()
app.launch()
app.pickers.elementAtIndex(0).swipeUp()
XCTAssert(app.staticTexts["Selected: Black"].exists)
改变选择器视图的另一种但非常相似的方法是调用pressForDuration ... thenDragToElement
,这不是我想要的。
app.pickers.elementAtIndex(0).pressForDuration(0.1, thenDragToElement: someElement)
当我使用UI测试记录功能时,它不会记录选择器视图滚动事件。当我点击选择器视图项时它会记录:
app.pickerWheels["Green"].tap()
但是在运行测试时这实际上并不起作用(可能是因为它需要在点击之前首先滚动选择器视图)。
这是带有测试的演示应用程序。
https://github.com/exchangegroup/PickerViewTestDemo
现在可以从Xcode 7.0 beta 6中选择一个选择器视图。
app.pickerWheels["Green"].adjustToPickerWheelValue("Yellow")
正如问题的更新中所述,Xcode 7 Beta 6增加了对与拾取器交互的支持。新添加的方法-adjustToPickerWheelValue:
应该用于选择UIPickerView
上的项目。
let app = XCUIApplication()
app.launch()
app.pickerWheels.element.adjustToPickerWheelValue("Yellow")
这是一个GitHub repo with a working example。还有一些more information in a blog post I wrote。
如果有多个轮子,一个简单的方法来选择项目是这样的:
前提条件:它是一个日期选择器(UIDatePicker),快速的语言
app.pickerWheels.elementBoundByIndex(0).adjustToPickerWheelValue("March")
app.pickerWheels.elementBoundByIndex(1).adjustToPickerWheelValue("13")
app.pickerWheels.elementBoundByIndex(2).adjustToPickerWheelValue("1990")
其中:索引“0”是月,“1”是日,“2”是年
Swift 4版@ Joao_dche的答案
app.pickerWheels.element(boundBy: 0).adjust(toPickerWheelValue: "March")
app.pickerWheels.element(boundBy: 1).adjust(toPickerWheelValue: "13")
app.pickerWheels.element(boundBy: 2).adjust(toPickerWheelValue: "1990")
@ Joao_dche的答案的Objective-C版本
使用UIDatePicker和XCTest进行UI测试:
XCUIElementQuery *datePickersQuery = app.datePickers;
[datePickersQuery.pickerWheels.allElementsBoundByIndex[0] adjustToPickerWheelValue:@"May"];
[datePickersQuery.pickerWheels.allElementsBoundByIndex[1] adjustToPickerWheelValue:@"13"];
[datePickersQuery.pickerWheels.allElementsBoundByIndex[2] adjustToPickerWheelValue:@"2017"];
XCUIElement *doneButton = app.buttons[@"Done"];
[doneButton.firstMatch tap];
Joe's answer在iOS 11上运行良好,但在iOS 10.3.1上不适用于我[Xcode 9.2]
我使用自定义视图(实际上是标签)作为选择器行,不幸的是,华丽的Joe的答案在iOS 10.3.1上对我不起作用,同时在iOS 11上完美运行。所以我不得不使用
app.pickerWheels["X, Y of Z"].swipeUp()
哪里
X is my label's text.
Y is row position in picker view. Position number starts with 1, not zero.
Z is number of values in picker view.
所以在我的情况下,这个命令看起来像
app.pickerWheels["1st, 1 of 28"].swipeUp()
我使用下面的代码来识别拾取轮中现在显示的元素。
let valueSelected = algorithmsPicker.pickerWheels.element(boundBy: 0).value as! String
algorithmsPicker.pickerWheels[valueSelected].adjust(toPickerWheelValue: "BubbleSort")