gpt4 book ai didi

ios - Xcode UI 测试发现多个按钮

转载 作者:搜寻专家 更新时间:2023-11-01 06:16:18 24 4
gpt4 key购买 nike

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

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

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

app.children(matching: .window).element(boundBy: 0).children(matching: .other).element(boundBy: 1).buttons["Upgrade"].tap()

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

知道为什么会这样吗?

有时在调试器中运行 p UIApplication.shared.windows 时,数组中有 2 个值。我不确定为什么,因为我从来没有多个窗口。我与 Windows 的唯一交互是有时将 UIApplication.shared.keyWindow?.rootViewController 设置为不同的 View Controller ,以及 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()

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

最佳答案

出现此消息是因为屏幕上有多个按钮具有 accessibilityIdentifieraccessibilityLabel value,“升级”,所以它无法确定要点击哪个。

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

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

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

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

// test code
let app = XCUIApplication()
let upgradeButton = app.buttons["upgradeButton"]
upgradeButton.tap()

在屏幕上同时出现多个相同升级按钮的情况下(例如,按钮是屏幕上重复图案的一部分,比如有很多产品待售),没关系它们每个都具有相同的 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()

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

// 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()

关于ios - Xcode UI 测试发现多个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44252162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com