iOS XCUIT通过辅助功能访问元素

时间:2017-01-03 11:52:45

标签: ios swift xctest

如何通过accessibilityLabel或标识符声明按钮存在?

func testExitsButton() {
    XCTAssertTrue(app.windows.containing(.button, identifier: "Button Text").element.exists)
    XCTAssertTrue(app.buttons["Button Text"].exists)
    XCTAssertTrue(app.buttons["test"].exists) <- I want this, instead of accessing the text property I want by specific id, maybe the text property override the accessibilityLabel?
}

enter image description here

4 个答案:

答案 0 :(得分:21)

在应用程序代码中设置辅助功能标识符,然后在测试中使用该标识符搜索该按钮。

// app code
let button: UIButton!
button.accessibilityIdentifier = "myButton"

// UI test code
func testMyButtonIsDisplayed() {
    let app = XCUIApplication()
    let button = app.buttons["myButton"]
    XCTAssertTrue(button.exists)
}

可访问性标识符的设置与按钮上的文本无关,也与可访问性标签无关。将UI元素的标识符作为辅助功能标签放入最佳实践不是最佳做法,因为可访问性标签会被VoiceOver用户读取以向其解释元素。

答案 1 :(得分:10)

重要提示:如果将超级视图设置为可访问,则XCUITest可能无法访问其子视图。

您可以通过故事板或以编程方式设置其可访问性来访问该元素,如上所述。当光标位于以前缀“test”开头的函数中时,可以单击记录按钮,以记录XCUITest如何看到元素。有时它需要一些清理(命令转换k)和几分钟的记录按钮可用。您还可以从故事板中逐步下载树并使用XCUITest函数(如element(boundBy:Int),子元素(匹配:.textField)),也可以将它们链接起来:XCUIApplication()。tables.cells.containing(.button,标识符:“id”)。在那之后是简单的部分,使用返回布尔值的.exists。

enter image description here

答案 2 :(得分:7)

添加| &#34; accessibilityIdentifier&#34;字符串测试|在导航栏上的用户定义的运行时属性中,而不是在辅助功能标签

答案 3 :(得分:0)

我遇到了同样的问题,因为键盘盖住了按钮,所以:

app.buttons["Done"].tap()

解决了这个问题。