在Swift 3 UI测试中访问自定义视图组件中的元素

时间:2017-04-27 13:11:40

标签: ios iphone unit-testing swift3 xcode-ui-testing

我是任何类型iOS编程的新手。我正在尝试为我的一个场景编写UI测试用例。

以下是我在使用recode方法并点击自定义组件时获得的代码。

let button = XCUIApplication().children(matching: .window).element(boundBy: 0).children(matching: .other).element.children(matching: .button).element

在此自定义组件中有两个按钮。我想知道选择了哪个按钮。为此我需要识别按钮。但是,我点击自定义视图时会得到相同的代码。

如何访问自定义视图中的每个组件。任何帮助都会很棒。

2 个答案:

答案 0 :(得分:7)

在应用的代码中为自定义视图添加辅助功能标识符。

let customView: UIView!
customView.accessibilityIdentifier = "myCustomView"

然后访问如下内容:

let app = XCUIApplication()
let customView = app.otherElements["myCustomView"]
let button1 = customView.buttons.element(boundBy: 0)
let button2 = customView.buttons.element(boundBy: 1)
XCTAssertTrue(button1.isSelected)
XCTAssertFalse(button2.isSelected)

请注意,要使测试具有确定性,您应该已经知道应该选择哪个按钮。这可确保您的测试在每次运行时都测试相同的内容。

答案 1 :(得分:0)

您需要使元素对辅助功能可见。

我建议你观看WWDC Session about UI Testing in Xcode,尤其是this part