Testing Text Fields, Buttons, and Labels - UI Testing - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 9. UI Testing

9.3 Testing Text Fields, Buttons, and Labels

Problem

You want to create UI tests to work with instances of UITextField, UIButton, and UILabel.

Solution

All the aforementioned items are instances of type XCUIElement. That means that you can work with some really cool properties of them in UI testing such as the followings:

§ exists

§ title

§ label

§ enabled

§ frame

§ debugDescription

§ descendantsMatchingType(_:)

§ childrenMatchingType(_:)

The last two in the list are a bit more advanced than what I’d like to discuss in this recipe, so we are going to talk about them later in this chapter when we discuss queries.

Discussion

Let’s say that you have a label and a button. When the button is pressed, you are hiding the label (by setting its hidden property to true). You now want to write a UI test to see whether the desired effect actually happens. I assume that you’ve already set up your UI and you’ve given an accessibility label of “Button” to the button and “Label” to the label.

NOTE

I recommend that you do as much as possible in Xcode’s automated recording system, where you can just visually see your UI and then let Xcode write your UI test code for you. So I will do that, not only in this recipe, but as much as possible in all other recipes in this book if appropriate.

So open the recording section of UI tests (see Figure 9-5) and press on the button. The code that you’ll get will be similar to this:

let app = XCUIApplication()

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

You can see that the app object has a property called buttons that returns an array of all buttons that are on the screen. That itself is awesome, in my opinion. Then the tap() method is called on the button. We want to find the label now:

let lbl = app.staticTexts["Label"]

As you can see, the app object has a property called staticTexts that is an array of labels. Any label, anywhere. That’s really cool and powerful. Regardless of where the label is and who is the parent of the label, this property will return that label. Now we want to find whether that label is on screen:

XCTAssert(lbl.exists == false)

You can of course also read the value of a text field. You can also use the debugger to inspect the value property of a text field element using the po command. You can find all text fields that are currently on the screen using the textFields property of the app that you instantiated withXCUIApplication().

Here is an example where I try to find a text field on the screen with a specific accessibility label that I have set in my storyboard:

let app = XCUIApplication()

let txtField = app.textFields["MyTextField"]

XCTAssert(txtField.exists)

XCTAssert(txtField.value != nil)

let txt = txtField.value as! String

XCTAssert(txt.characters.count > 0)

See Also