Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a right item button on navigation bar in XCUITest?

I am writing UITest cases for my iOS Swift app. In the app I have created a custom right item button on the navigation bar in this way:

let barButtonItem = UIBarButtonItem(customView: customView)
navigationItem.rightBarButtonItem = barButtonItem

Now I don't know how to access this custom right item button in XCUITest and really need some help. Thanks in advance.

like image 458
Zhengqian Kuang Avatar asked Jan 09 '19 19:01

Zhengqian Kuang


1 Answers

You cannot access a UIBarButtonItem, because it is not a real UIElement (it is not a UIView subclass), but you probably want to access the UIButton inside your right bar button item anyway.

There are several ways how you could access the button, here are two ideas:

1. Query the first button in the navigation bar

let rightNavBarButton = XCUIApplication().navigationBars.children(matching: .button).firstMatch
XCTAssert(rightNavBarButton.exists)

That way you access the first UIButton inside a UINavigationBar.

This only works if there is only one button in your navigation bar. So it will break when you add another button.

2. Use an accessibility identifier

You can define a accessibility identifier for the button inside your right bar button item and use that to access it during the test:

In your app:

let barButtonItem = UIBarButtonItem(customView: customView)
barButtonItem.accessibilityIdentifier = "navbarRightItem"
navigationItem.rightBarButtonItem = barButtonItem

In your test:

let rightNavBarButton = XCUIApplication().navigationBars.buttons["navbarRightItem"]
XCTAssert(rightNavBarButton.exists)

Just make sure you are using accessibilityIdentifier and not accessibilityLabel. Because accessibilityLabel will be read by VoiceOver for handicapped users and should contain useful text.

like image 76
joern Avatar answered Sep 28 '22 14:09

joern