2017-05-30 75 views
1

我遇到了一個問題,在使用以下代碼時,我的UI測試顯示找到了多個按鈕。Xcode 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。出現

+0

打印'app.buttons [「Upgrade」]。debugDescription'可能提供提示... –

+1

我想我以前遇到過這個問題。您可以嘗試在您正在測試的按鈕上拋出唯一的輔助功能標識符,然後重新記錄測試。 – Adrian

+0

@PauloMattos我設置了一個斷點並試圖打印,但它打印了很多東西。我迅速瀏覽了它,找不到任何有用的東西或者我不知道的東西。 –

回答

2

此消息,因爲在屏幕上的多個按鈕與accessibilityIdentifieraccessibilityLabelvalue,「升級」,因此它不能工作了挖掘其中之一。

它當您使用錄製的版本,因爲記錄工具已經確定,搜索需要被縮小在指數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() 
+0

這根本沒有意義。我相信,在當前的視圖控制器中,我只有一個按鈕,其值爲「升級」。我也發現這隻發生在iPhone 4S上。 –

0

,因爲升級到8.3的XCode在XCUIElementQuery是返回多個結果時應該只有一個我看到了類似的問題。這個版本中可能會引入一個錯誤。

https://forums.developer.apple.com/thread/75546 描述的bug和雷達是在這裏: https://openradar.appspot.com/31498932

我試圖強迫我的查詢返回所需的對象爲XCUIElementQuery,然後使用element(boundBy:)嘗試張貼的解決辦法,它工作了我。

令人不安的是UI測試的不穩定性。

0

我面臨同樣的問題,並試圖擺脫它的多種事情。最終我發現當我更新我的Xcode到8.3.3和模擬器os到iOS 10.3時,問題開始發生。 切換我的模擬器操作系統回到iOS 10.2,它的工作完美。