Contact
← Back to Topics

XCTest

Apple's testing framework for writing unit, performance, and UI tests for iOS apps.

About XCTest

XCTest is Apple's native testing framework for iOS, macOS, watchOS, and tvOS applications. It allows developers to write unit tests, performance tests, and UI tests to ensure app quality and prevent regressions.

Key Features

  • Unit testing
  • UI testing with XCUITest
  • Performance testing
  • Asynchronous testing
  • Test expectations

Code Example

// XCTest examples
import XCTest
@testable import MyApp

// Unit Test
class CalculatorTests: XCTestCase {
    var calculator: Calculator!
    
    override func setUp() {
        super.setUp()
        calculator = Calculator()
    }
    
    override func tearDown() {
        calculator = nil
        super.tearDown()
    }
    
    func testAddition() {
        // Given
        let a = 5
        let b = 3
        
        // When
        let result = calculator.add(a, b)
        
        // Then
        XCTAssertEqual(result, 8, "Addition failed")
    }
    
    func testAsyncOperation() {
        // Create expectation
        let expectation = XCTestExpectation(description: "Async operation completes")
        
        calculator.calculateWithDelay { result in
            // Verify result
            XCTAssertEqual(result, 42)
            expectation.fulfill()
        }
        
        // Wait for expectation for max 2 seconds
        wait(for: [expectation], timeout: 2.0)
    }
    
    func testPerformance() {
        measure {
            // Code to measure
            calculator.complexCalculation()
        }
    }
}

// UI Test
class MyAppUITests: XCTestCase {
    var app: XCUIApplication!
    
    override func setUp() {
        super.setUp()
        app = XCUIApplication()
        app.launch()
    }
    
    func testLoginFlow() {
        // Enter credentials
        let usernameField = app.textFields["username"]
        usernameField.tap()
        usernameField.typeText("testuser")
        
        let passwordField = app.secureTextFields["password"]
        passwordField.tap()
        passwordField.typeText("password123")
        
        // Tap login button
        app.buttons["login"].tap()
        
        // Verify dashboard is shown
        XCTAssertTrue(app.navigationBars["Dashboard"].exists)
    }
}