簡體   English   中英

Xcode UI測試找到的多個按鈕

[英]Xcode UI Tests Multiple Buttons Found

我遇到一個問題,我的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設置為不同的視圖控制器,以及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 ,“ Upgrade”的按鈕,因此無法確定要點擊哪個按鈕。

使用記錄版本時它起作用的原因是,記錄工具已確定需要縮小搜索范圍以在索引1 .other類型的元素內進行搜索,以確保確定哪個“升級”按鈕與之互動。

窗口不是問題,而是按鈕標識符的唯一性以及在測試中如何處理它們。

如果按鈕僅在相關應用頁面上使用一次,則最好在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()

在這種情況下,您還可以采用以下方法:找到正確的容器視圖,並在其中搜索升級按鈕。

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

自從更新到XCode 8.3以來,我看到了類似的問題,在XCode 8.3中,當應該只有一個時, XCUIElementQuery返回多個結果。 此版本中可能引入了一個錯誤。

https://forums.developer.apple.com/thread/75546描述了該錯誤,雷達位於此處: https : //openradar.appspot.com/31498932

我嘗試過強制執行查詢以將所需對象作為XCUIElementQuery ,然后使用element(boundBy:)來嘗試發布的解決方法,它對我element(boundBy:)

UI測試的不穩定程度令人不安。

我遇到了同樣的問題,並嘗試了多種解決方案。 最終,我發現當我將Xcode更新為8.3.3,並將模擬器os更新為iOS 10.3時,該問題開始發生。 將我的模擬器操作系統切換回iOS 10.2,它運行良好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM