我对@deepak-terse 的回答有一个补充:
您可以使用索引而不是字符串文件名,因此您不依赖于模拟器。
func selectFromCameraRoll(_ app: XCUIApplication, index: Int = 1) {
app.tables.cells.element(boundBy: 1).tap()
app.collectionViews.cells.element(boundBy: index).tap()
}
您甚至可以使用随机化您选择的照片arc4random_uniform()
更新
如果有人发现这个有用,这是我在真实设备上测试时使用的 UI 测试中相机的辅助函数:
func addPhotoCamera(_ app: XCUIApplication) {
let pleaseSelectSheet = app.sheets.element
// Take Picture button, it is first:
pleaseSelectSheet.buttons.element(boundBy: 0).tap()
// this monstrosity finds Capture button
let element = app
.children(matching: .window).element(boundBy: 0)
.children(matching: .other).element
.children(matching: .other).element
.children(matching: .other).element
.children(matching: .other).element
let photoCapture = element.children(matching: .other).element
.children(matching: .other).element(boundBy: 1)
.children(matching: .other).element
photoCapture.tap()
// I have slow computer, so I need this so test does not fail
sleep(5)
app.buttons["Use Photo"].tap()
}
更新 2
在设备上,上面的相机胶卷不起作用,因为通常有很多照片,所以先点击不在屏幕上的照片将无济于事。我最终使用了以下代码段:
let photoCells = app.collectionViews.cells
if Platform.isSimulator {
photoCells.element(boundBy: index).tap()
} else {
photoCells.allElementsBoundByIndex.last!.firstMatch.tap()
}
其中Platform.isSimulator
部分来自https://stackoverflow.com/a/30284266/2875219:
import Foundation
struct Platform {
static var isSimulator: Bool {
return TARGET_OS_SIMULATOR != 0
}
}
和整段代码在一起:
struct Platform {
static var isSimulator: Bool {
return TARGET_OS_SIMULATOR != 0
}
}
extension XCUIElement {
func tapIfExists() {
if exists {
tap()
}
}
}
// MARK: - Helper functions
extension XCTestCase {
func addPhotoCamera(_ app: XCUIApplication) {
let pleaseSelectSheet = app.sheets.element
// ["Take Picture"].tap()
pleaseSelectSheet.buttons.element(boundBy: 0).tap()
// use coordinates and tap on Take picture button
let element = app
.children(matching: .window).element(boundBy: 0)
.children(matching: .other).element
.children(matching: .other).element
.children(matching: .other).element
.children(matching: .other).element
let photoCapture = element.children(matching: .other).element
.children(matching: .other).element(boundBy: 1)
.children(matching: .other).element
photoCapture.tap()
sleep(5)
app.buttons["Use Photo"].tap()
}
func addPhotoLibrary(_ app: XCUIApplication, index: Int = 0) {
let pleaseSelectSheet = app.sheets["Add Photo"]
pleaseSelectSheet.buttons.element(boundBy: 1).tap()
sleep(10)
// Camera Roll
app.tables.cells.element(boundBy: 1).tap()
sleep(2)
let photoCells = app.collectionViews.cells
if Platform.isSimulator {
photoCells.element(boundBy: index).tap()
} else {
photoCells.allElementsBoundByIndex.last!.firstMatch.tap()
}
sleep(2)
app.buttons["Choose"].tapIfExists()
}
}