0
0
Swiftprogramming~5 mins

XCTest framework basics in Swift

Choose your learning style9 modes available
Introduction

XCTest helps you check if your Swift code works correctly by running tests automatically.

You want to make sure a function returns the right result.
You want to check if your app handles errors properly.
You want to test if your code changes break anything.
You want to run tests automatically when you build your app.
Syntax
Swift
import XCTest

final class MyTests: XCTestCase {
    func testExample() {
        // Your test code here
        XCTAssertEqual(2 + 2, 4)
    }
}

Test classes must inherit from XCTestCase.

Test methods start with test and have no parameters or return value.

Examples
Checks if 3 + 4 equals 7.
Swift
func testSum() {
    XCTAssertEqual(3 + 4, 7)
}
Checks if a value is not nil.
Swift
func testNotNil() {
    let value: String? = "Hello"
    XCTAssertNotNil(value)
}
Checks if a function throws an error as expected.
Swift
func testThrows() {
    XCTAssertThrowsError(try someFunctionThatThrows())
}
Sample Program

This program tests simple addition and subtraction using XCTest.

Swift
import XCTest

final class CalculatorTests: XCTestCase {
    func testAddition() {
        let sum = 2 + 3
        XCTAssertEqual(sum, 5)
    }

    func testSubtraction() {
        let difference = 5 - 3
        XCTAssertEqual(difference, 2)
    }
}

// Normally XCTest runs tests automatically in Xcode.
// For playground or command line, you can run tests manually like this:
CalculatorTests.defaultTestSuite.run()
OutputSuccess
Important Notes

Use XCTAssert functions to check conditions in tests.

Test methods must start with test to be recognized.

Run tests often to catch bugs early.

Summary

XCTest helps you write tests to check your Swift code.

Test classes inherit from XCTestCase and test methods start with test.

Use assertions like XCTAssertEqual to verify results.