SyntaxStudy
Sign Up
Swift Testing and Assertions
Swift Beginner 1 min read

Testing and Assertions

XCTest is Swift's built-in testing framework. Test classes inherit from XCTestCase, and test methods are prefixed with test. XCTAssert family of functions verify expectations. XCTAssertThrowsError verifies that a function throws, and XCTAssertNoThrow verifies it doesn't. You can inspect the thrown error for more detailed validation. Swift Testing (introduced in Xcode 16) uses @Test macro and #expect for a more modern testing experience with better error messages and parallel execution.
Example
import XCTest

// Class under test
struct Calculator {
    enum CalcError: Error { case divisionByZero }
    func divide(_ a: Double, by b: Double) throws -> Double {
        guard b != 0 else { throw CalcError.divisionByZero }
        return a / b
    }
    func add(_ a: Double, _ b: Double) -> Double { a + b }
}

// XCTest
class CalculatorTests: XCTestCase {
    var sut: Calculator!

    override func setUp() {
        super.setUp()
        sut = Calculator()
    }

    override func tearDown() {
        sut = nil
        super.tearDown()
    }

    func testAddition() {
        XCTAssertEqual(sut.add(2, 3), 5)
        XCTAssertEqual(sut.add(-1, 1), 0)
    }

    func testDivision() throws {
        let result = try sut.divide(10, by: 2)
        XCTAssertEqual(result, 5, accuracy: 0.001)
    }

    func testDivisionByZeroThrows() {
        XCTAssertThrowsError(try sut.divide(5, by: 0)) { error in
            XCTAssertTrue(error is Calculator.CalcError)
        }
    }

    func testPerformance() {
        measure {
            for _ in 0..<1000 { _ = sut.add(1.5, 2.5) }
        }
    }
}