0
0
iOS Swiftmobile~5 mins

XCTest framework in iOS Swift

Choose your learning style9 modes available
Introduction

The XCTest framework helps you check if your iOS app works correctly by running tests automatically.

To make sure a button tap changes the screen as expected.
To verify that a function returns the right result.
To catch bugs early before users find them.
To test if your app handles errors properly.
To check if your app's data saves and loads correctly.
Syntax
iOS Swift
import XCTest

class MyTests: XCTestCase {
    func testExample() {
        XCTAssertEqual(2 + 2, 4)
    }
}

Tests are written inside classes that inherit from XCTestCase.

Each test function starts with test and uses assertions like XCTAssertEqual to check results.

Examples
This test checks if adding 3 and 4 equals 7.
iOS Swift
func testSum() {
    let result = 3 + 4
    XCTAssertEqual(result, 7)
}
This test checks that the variable name is not nil.
iOS Swift
func testNotNil() {
    let name: String? = "Alice"
    XCTAssertNotNil(name)
}
This test checks if the condition isReady is true.
iOS Swift
func testTrueCondition() {
    let isReady = true
    XCTAssertTrue(isReady)
}
Sample App

This test class checks two simple math operations: addition and subtraction. Each test confirms the result is correct.

iOS Swift
import XCTest

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

    func testSubtraction() {
        let difference = 10 - 4
        XCTAssertEqual(difference, 6)
    }
}
OutputSuccess
Important Notes

Always name test functions starting with test so XCTest can find them.

Use different XCTAssert functions to check various conditions like equality, nil, true/false.

Run tests often to catch problems early and keep your app reliable.

Summary

XCTest helps you write tests to check your app's behavior automatically.

Tests are functions inside classes that extend XCTestCase.

Use assertions like XCTAssertEqual to verify expected results.