2017-01-03 155 views
5

我如何斷言他的accesibilityLabel或標識符存在的按鈕?iOS XCUITests通過訪問元素訪問元素

func testExitsButton() { 
    XCTAssertTrue(app.windows.containing(.button, identifier: "Button Text").element.exists) 
    XCTAssertTrue(app.buttons["Button Text"].exists) 
    XCTAssertTrue(app.buttons["test"].exists) <- I want this, instead of accesing the text property i want by specific id, maybe the text property override the accesibiltyLabel? 
} 

enter image description here

回答

11

在應用程序代碼中設置一個輔助標識,然後搜索使用您的測試,標識的按鈕。

// app code 
let button: UIButton! 
button.accessibilityIdentifier = "myButton" 

// UI test code 
func testMyButtonIsDisplayed() { 
    let app = XCUIApplication() 
    let button = app.buttons["myButton"] 
    XCTAssertTrue(button.exists) 
} 

輔助功能標識符獨立於按鈕上的文本設置,也獨立於輔助功能標籤。將UI元素的標識設置爲標籤不是最佳做法,因爲可讀性標籤將讀取給VoiceOver用戶以向他們解釋元素。

+0

Thx!如果您不設置任何輔助功能標識/標籤,您是否可以通過其文本訪問UIButton? – Godfather

+0

您可以,但這不是最佳實踐,因爲如果您決定更改或本地化文本,則需要進行維護。 – Oletha

+0

so app.buttons [「id」]首先嚐試訪問「id」accessibilityIdentifier,如果沒有設置,則搜索「id」文本屬性? – Godfather

3

重要提示:如果超級視圖設置爲可訪問,XCUITest可能無法訪問其子視圖。

如上所述,您可以通過故事板或編程設置其可訪問性來訪問該元素。當光標位於以「test」開頭的函數中時,您可以單擊記錄按鈕,以記錄XCUITest如何看到某個元素。有時需要幾次清理(命令轉移k)和幾分鐘才能使記錄按鈕可用。您還可以從故事板中放下樹,並使用XCUITest函數(如元素(boundBy:Int),children(匹配:.textField)),還可以鏈接它們:XCUIApplication()。tables.cells.containing(.button,標識符:「id」)。在那之後是簡單的部分,使用返回布爾值的.exists。

enter image description here

+2

第一句話提供了非常有用的信息,並且結束了一個小時的搜索錯誤。 –

+0

很高興聽到@NilsHott – ScottyBlades

+0

這100萬次! –

1

add | 「accessibilityIdentifier」字符串測試|在導航欄上的「用戶定義的運行時屬性」中,而不是在輔助功能標籤中,而不是在輔助功能標籤中