Writing reliable Swift code starts with tests you can trust. This guide covers everything from the foundations of XCTest to modern Swift Testing patterns.
XCTest is Apple's native testing framework, bundled directly into Xcode and available across all Apple platforms — iOS, macOS, watchOS, tvOS, and visionOS. It has been the standard tool for unit testing Swift (and Objective-C) code since Xcode 5, and it remains the backbone of automated quality assurance in the Apple ecosystem.
At its heart, XCTest exists to let you verify that your code does exactly what you intend it to do — not just today, but after every future change. It serves several concrete goals:
testLoginFailsWithEmptyPassword() tells the next developer (or future you) exactly what the system is supposed to do without requiring them to read through implementation details.A test lives inside a class that inherits from XCTestCase. Each test method must start with the word test, take no arguments, and return void.
import XCTest
@testable import MyApp
final class CurrencyFormatterTests: XCTestCase {
var formatter: CurrencyFormatter!
// MARK: - Lifecycle
override func setUp() {
super.setUp()
formatter = CurrencyFormatter(locale: Locale(identifier: "en_US"))
}
override func tearDown() {
formatter = nil
super.tearDown()
}
// MARK: - Tests
func testFormatsPositiveAmountCorrectly() {
let result = formatter.string(from: 1_234.56)
XCTAssertEqual(result, "$1,234.56")
}
func testFormatsZeroAsZeroDollars() {
let result = formatter.string(from: 0)
XCTAssertEqual(result, "$0.00")
}
func testFormatsNegativeAmountWithMinusSign() {
let result = formatter.string(from: -99.99)
XCTAssertEqual(result, "-$99.99")
}
}
XCTest provides a rich set of assertion functions: