无法从图库XCUITest中选择图像

时间:2020-09-30 09:22:54

标签: ios swift xcode xcuitest

我使用XCUITest来测试一个应用,该应用允许用户通过从图库中选择照片来选择头像。当我点击打开图库窗口的按钮时,我可以看到debugDescription中的元素。有一个表格,其中包含带照片的文件夹。问题是,当我第一次在任何单元格上点击时,测试失败并显示错误:

Assertion Failure: UserProfileAndSettingsTests.swift:434: Failed to get matching snapshot: No matches found for Element at index 2 from input {(
    Table
)}".  

如果我在此处放置一个断点,则第二次点击任意一个单元格,它将起作用。

命令如下:

XCUIApplication().tables.element(boundBy: 2).cells.element(boundBy: 1).tap()

如果在命令之前我输入以下行:XCUIApplication().tables.element(boundBy: 2).cells.element(boundBy: 1),则它不会失败。尝试tap()时失败。

1 个答案:

答案 0 :(得分:0)

看起来像是时间问题。熟悉XCUIElement类,尤其是这个:

/** Waits the specified amount of time for the element's exist property to be true and returns false if the timeout expires without the element coming into existence. */
    open func waitForExistence(timeout: TimeInterval) -> Bool

您应该能够执行以下操作:

let element = XCUIApplication().tables.element(boundBy: 2).cells.element(boundBy: 1)
if element.waitForExistence(timeout: 2) {
   element.tap()
}

我建议使用这种方法以及其他类似的方法和期望结识朋友,以便能够进行这样的便捷操作(在这种情况下,self是XCTestCase):

func waitUntilTappable(_ element:XCUIElement, timeout: TimeInterval = 2) {
   let tappableExpectation = self.expectation(for: NSPredicate(format: "isHittable == true"),
                                                        evaluatedWith: element)
   self.wait(for: [tappableExpectation], timeout: timeout.rawValue)
}