Bird
Raised Fist0
iOS Swiftmobile~20 mins

UI testing with XCUITest in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Simple Counter
A screen with a label showing a number and a button to increase the number by one each time it is tapped.
Target UI
---------------------
| Simple Counter     |
|-------------------|
|                   |
|       0           |
|                   |
|   [Increment]     |
---------------------
Display a label with initial number 0 centered on screen
Add a button labeled 'Increment' below the label
Tapping the button increases the number by 1 and updates the label
Write an XCUITest that launches the app, taps the Increment button 3 times, and verifies the label shows '3'
Starter Code
iOS Swift
import SwiftUI

struct ContentView: View {
    @State private var count = 0

    var body: some View {
        VStack(spacing: 20) {
            Text("\(count)")
                .font(.largeTitle)
                .accessibilityIdentifier("countLabel")
            Button("Increment") {
                // TODO: Increase count by 1
            }
            .accessibilityIdentifier("incrementButton")
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Task 1
Solution
iOS Swift
import SwiftUI

struct ContentView: View {
    @State private var count = 0

    var body: some View {
        VStack(spacing: 20) {
            Text("\(count)")
                .font(.largeTitle)
                .accessibilityIdentifier("countLabel")
            Button("Increment") {
                count += 1
            }
            .accessibilityIdentifier("incrementButton")
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

// XCUITest file
import XCTest

final class SimpleCounterUITests: XCTestCase {
    var app: XCUIApplication!

    override func setUpWithError() throws {
        continueAfterFailure = false
        app = XCUIApplication()
        app.launch()
    }

    func testIncrementButtonIncreasesCount() throws {
        let incrementButton = app.buttons["incrementButton"]
        let countLabel = app.staticTexts["countLabel"]

        XCTAssertEqual(countLabel.label, "0")

        incrementButton.tap()
        incrementButton.tap()
        incrementButton.tap()

        XCTAssertEqual(countLabel.label, "3")
    }
}

The SwiftUI view uses a @State variable count to hold the number. The Text shows the current count and has an accessibility identifier countLabel so the UI test can find it. The Button labeled "Increment" increases the count by 1 when tapped and has an accessibility identifier incrementButton.

The XCUITest launches the app, finds the button and label by their accessibility identifiers, taps the button 3 times, and checks that the label updates to "3". This confirms the UI behaves as expected.

Final Result
Completed Screen
---------------------
| Simple Counter     |
|-------------------|
|                   |
|       3           |
|                   |
|   [Increment]     |
---------------------
User taps the Increment button
The number in the label increases by 1 each tap
After 3 taps, the label shows '3'
Stretch Goal
Add a Reset button that sets the count back to 0
💡 Hint
Add another Button below Increment with label 'Reset' and set count = 0 in its action

Practice

(1/5)
1. What is the main purpose of using XCUITest in iOS app development?
easy
A. To automate user interface testing by simulating user actions
B. To write backend server code for the app
C. To design app icons and graphics
D. To manage app database connections

Solution

  1. Step 1: Understand XCUITest's role

    XCUITest is a framework designed to automate UI testing by simulating taps, typing, and other user interactions.
  2. Step 2: Eliminate unrelated options

    The options for designing app icons/graphics, writing backend server code, and managing database connections are incorrect, as they are not related to XCUITest's purpose of UI testing.
  3. Final Answer:

    To automate user interface testing by simulating user actions -> Option A
  4. Quick Check:

    UI testing = automate user actions [OK]
Hint: XCUITest automates what users do on the screen [OK]
Common Mistakes:
  • Confusing UI testing with backend development
  • Thinking XCUITest is for design or graphics
  • Assuming it manages databases
2. Which of the following is the correct way to launch the app in an XCUITest case?
easy
A. let app = UIApplication() app.start()
B. let app = XCUIApplication() app.launch()
C. let app = XCUIElement() app.open()
D. let app = XCUIApplication() app.run()

Solution

  1. Step 1: Recall correct class and method

    In XCUITest, XCUIApplication() creates the app instance, and launch() starts it.
  2. Step 2: Check method names and classes

    UIApplication and XCUIElement are incorrect for launching tests; start() and run() are not valid methods here.
  3. Final Answer:

    let app = XCUIApplication()\napp.launch() -> Option B
  4. Quick Check:

    Use XCUIApplication and launch() [OK]
Hint: XCUIApplication().launch() always starts the app in tests [OK]
Common Mistakes:
  • Using UIApplication instead of XCUIApplication
  • Calling non-existent methods like start() or run()
  • Confusing XCUIElement with the app instance
3. Given the following XCUITest code snippet, what will be the result?
let app = XCUIApplication()
app.launch()
let button = app.buttons["submitButton"]
if button.exists {
    button.tap()
    print("Tapped")
} else {
    print("Button not found")
}
medium
A. Always prints "Button not found" regardless of button presence
B. Prints "Tapped" even if the button does not exist
C. Causes a compile-time error due to incorrect syntax
D. Prints "Tapped" if the button with accessibility identifier "submitButton" exists

Solution

  1. Step 1: Analyze button existence check

    The code checks if the button with identifier "submitButton" exists using button.exists.
  2. Step 2: Understand conditional behavior

    If the button exists, it taps and prints "Tapped"; otherwise, it prints "Button not found".
  3. Final Answer:

    Prints "Tapped" if the button with accessibility identifier "submitButton" exists -> Option D
  4. Quick Check:

    Button exists? Tap and print "Tapped" [OK]
Hint: Check .exists before tap to avoid errors [OK]
Common Mistakes:
  • Assuming print always shows "Button not found"
  • Thinking code has syntax errors
  • Ignoring the existence check before tap
4. Identify the error in this XCUITest code snippet:
let app = XCUIApplication()
app.launch()
let textField = app.textFields["username"]
textField.typeText("user123")
app.buttons["login"].tap()
medium
A. Incorrect app launch method used
B. Using typeText instead of setText method
C. Missing check if textField exists before typing
D. Buttons cannot be tapped in XCUITest

Solution

  1. Step 1: Review element existence checks

    The code types text into a text field without verifying if it exists, which can cause test failures.
  2. Step 2: Confirm other method usages

    typeText is the correct method; app.launch() is correct; buttons can be tapped in XCUITest.
  3. Final Answer:

    Missing check if textField exists before typing -> Option C
  4. Quick Check:

    Always check element exists before interaction [OK]
Hint: Check .exists before typing or tapping [OK]
Common Mistakes:
  • Skipping existence checks causing crashes
  • Confusing typeText with non-existent methods
  • Thinking buttons can't be tapped in tests
5. You want to write an XCUITest that verifies a label updates after tapping a button. Which approach correctly waits for the label to change text before asserting?
let app = XCUIApplication()
app.launch()
let button = app.buttons["updateButton"]
let label = app.staticTexts["statusLabel"]
button.tap()
// What code waits for label text to change to "Done"?
hard
A. let exists = NSPredicate(format: "label == 'Done'") expectation(for: exists, evaluatedWith: label, handler: nil) waitForExpectations(timeout: 5, handler: nil)
B. sleep(5) assert(label.label == "Done")
C. while label.label != "Done" {} assert(true)
D. assert(label.label == "Done") immediately after tap

Solution

  1. Step 1: Understand waiting for UI changes

    Using NSPredicate with expectation waits properly for the label's text to become "Done" within timeout.
  2. Step 2: Evaluate other options

    sleep() is unreliable; busy-wait loop blocks test; immediate assert may fail if UI hasn't updated yet.
  3. Final Answer:

    let exists = NSPredicate(format: "label == 'Done'")\nexpectation(for: exists, evaluatedWith: label, handler: nil)\nwaitForExpectations(timeout: 5, handler: nil) -> Option A
  4. Quick Check:

    Use expectations to wait for UI updates [OK]
Hint: Use XCTest expectations to wait for UI changes [OK]
Common Mistakes:
  • Using sleep instead of expectations
  • Busy-wait loops freezing tests
  • Asserting UI state immediately after action
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard