1. Create simple project: Click on a button and then get the text in textfield for the label
- Add a text field, a button, and a label:
- Process the behavior when user tap on the button
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func buttonTapped(sender: AnyObject) {
label.text = textField.text
textField.resignFirstResponder()
}
}
2. Create new iOS UI Testing Bundle
- Click on your project
- Click + button to add new iOS UI Testing Bundle
- Select the iOS UI Testing Bundle
- New bundle will be here:
3. Recording your behaviors in simulator
-
Open the file: “UITestExampleUITests.swift”
-
Let your cursor within testExample() method, you will see the circle red button at the bottom of Xcode, press on it
- The simulator will be show and fill the text “testing” into the textfield and then click button:
- The
testExample()
method in UITestExampleUITests.swift will be filled as something like this:
func testExample() {
let app = XCUIApplication()
app.otherElements.containingType(.Button, identifier:"Button").childrenMatchingType(.TextField).element.typeText("testing")
app.buttons["Button"].tap()
}
- Turn of recording: Pressed on the circle has the red square inside
4. Add specific assert - [Test Here]
- Add this statement above of testExample() method
XCTAssert(app.staticTexts["testing"].exists)
This line mean: With the behavior we recorded (Item 3), the UI must be contain the text “testing”
- The testExample() method will be:
func testExample() {
let app = XCUIApplication()
app.otherElements.containingType(.Button, identifier:"Button").childrenMatchingType(.TextField).element.typeText("testing")
app.buttons["Button"].tap()
XCTAssert(app.staticTexts["testing"].exists)
}
5. Run test: Command + U
6. Basic statements:
- Waiting: Sometime you must to waiting for the animation done, or the results from network
func waitForElement(elementType: XCUIElement, timeout: NSTimeInterval ) {
let elementExist = NSPredicate(format: "exists == 1")
expectationForPredicate(elementExist, evaluatedWithObject: elementType, handler: nil)
waitForExpectationsWithTimeout(timeout, handler: nil)
}
- Get UITableViewCell
let app = XCUIApplication()
let cell = app.tables.staticTexts["About"] // This is a cell has content text: `About`