0
0
iOS Swiftmobile~7 mins

UI testing with XCUITest in iOS Swift

Choose your learning style9 modes available
Introduction

UI testing helps you check if your app looks and works right by simulating user actions automatically.

You want to make sure buttons and links respond correctly.
You need to test navigation between screens without tapping manually.
You want to catch bugs before users find them.
You want to check if text and images appear as expected.
You want to repeat tests easily after app updates.
Syntax
iOS Swift
import XCTest

class MyAppUITests: XCTestCase {
  let app = XCUIApplication()

  override func setUp() {
    super.setUp()
    continueAfterFailure = false
    app.launch()
  }

  func testExample() {
    app.buttons["MyButton"].tap()
    XCTAssertTrue(app.staticTexts["Welcome"].exists)
  }
}
Use XCUIApplication() to control your app in tests.
Use accessibility identifiers to find UI elements easily.
Examples
Taps a button labeled "Login".
iOS Swift
app.buttons["Login"].tap()
Checks if a text "Hello" is visible on screen.
iOS Swift
XCTAssertTrue(app.staticTexts["Hello"].exists)
Taps the username field and types text into it.
iOS Swift
app.textFields["Username"].tap()
app.textFields["Username"].typeText("user123")
Sample App

This test launches the app, taps a button named "ShowMessage", and checks if the label "Hello, World!" appears.

iOS Swift
import XCTest

class SimpleUITest: XCTestCase {
  let app = XCUIApplication()

  override func setUp() {
    super.setUp()
    continueAfterFailure = false
    app.launch()
  }

  func testTapButtonShowsLabel() {
    app.buttons["ShowMessage"].tap()
    XCTAssertTrue(app.staticTexts["Hello, World!"].exists)
  }
}
OutputSuccess
Important Notes

Always set accessibility identifiers in your app for UI elements to make testing easier.

Use continueAfterFailure = false to stop tests immediately when something fails.

Run UI tests on a simulator or real device to see how your app behaves.

Summary

UI testing with XCUITest lets you automate tapping, typing, and checking UI elements.

Use accessibility identifiers to find buttons, labels, and fields in tests.

Write tests to catch UI problems early and save time on manual testing.