Xcode UI 测试发现多个按钮

Cha*_*ish 1 xcode ios swift xcode-ui-testing

我遇到了一个问题,我的 UI 测试显示在使用以下代码时找到了多个按钮。

app.buttons["Upgrade"].tap()
Run Code Online (Sandbox Code Playgroud)

所以我重新运行我的单元测试并在运行该行之前设置一个断点并点击记录按钮并单击该按钮并生成以下代码。

app.children(matching: .window).element(boundBy: 0).children(matching: .other).element(boundBy: 1).buttons["Upgrade"].tap()
Run Code Online (Sandbox Code Playgroud)

当然在测试的顶部我有let app = XCUIApplication()

知道为什么会发生这种情况吗?

有时p UIApplication.shared.windows在调试器中运行时,数组中有 2 个值。我不知道为什么,因为我从来没有多个窗口。我与 Windows 的唯一交互UIApplication.shared.keyWindow?.rootViewController有时是设置为不同的视图控制器,以下代码在didFinishLaunchingWithOptions.

// Get view controllers ready
self.window = UIWindow(frame: UIScreen.main.bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let mainViewController: ViewController = mainStoryboard.instantiateViewController(withIdentifier: "FirstView") as! ViewController
// Show view controller
self.window?.rootViewController = mainViewController
self.window?.makeKeyAndVisible()
Run Code Online (Sandbox Code Playgroud)

那是在 if 语句和 else 语句中,我有几乎相同的代码,除了FirstView它是SecondView.

Ole*_*tha 5

出现此消息是因为屏幕上有多个带有accessibilityIdentifieraccessibilityLabel 或 的 value“升级”按钮,因此无法确定点击哪一个。

当您使用录制版本时它起作用的原因是因为录制工具已经确定需要缩小搜索范围.other以在 index 处的 type 元素内进行搜索1,以便确定要与哪个“升级”按钮进行交互.

这不是您的窗口的问题,而是您的按钮标识符的唯一性,以及您在测试中如何处理它们。

如果按钮在相关应用的页面上仅使用一次,最好accessibilityIdentifierUIButton. 它的值在您的应用程序的该页面中应该是唯一的,因此请确保您没有在其他任何地方使用相同的字符串。然后您可以明确访问该按钮:

// app code
let upgradeButton: UIButton!
upgradeButton.accessibilityIdentifier = "upgradeButton"

// test code
let app = XCUIApplication()
let upgradeButton = app.buttons["upgradeButton"]
upgradeButton.tap()
Run Code Online (Sandbox Code Playgroud)

如果屏幕上同时有多个相同升级按钮的实例(例如,该按钮是屏幕上重复图案的一部分,例如有很多产品要出售),则每个实例都可以具有相同的accessibilityIdentifier,但您应该更改在测试中访问元素的方式,element(boundBy:)用于访问指定索引处的项目:

// app code
let upgradeButton: UIButton!
upgradeButton.accessibilityIdentifier = "upgradeButton"

// test code
let app = XCUIApplication()
let upgradeButton = app.buttons["upgradeButton"].element(boundBy: 1) // second upgrade button
upgradeButton.tap()
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您也可以采取寻找正确的容器视图,并在其中搜索升级按钮的方法。

// test code
let app = XCUIApplication()
let upgradeButtonContainer = app.descendants(matching: .any).containing(.button, identifier: "upgradeButton").element(boundBy: 1) // second upgrade button-containing element
let upgradeButton = upgradeButtonContainer.buttons["upgradeButton"]
upgradeButton.tap()
Run Code Online (Sandbox Code Playgroud)