Introduction
XCTest helps you check if your Swift code works correctly by running tests automatically.
XCTest helps you check if your Swift code works correctly by running tests automatically.
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.
func testSum() { XCTAssertEqual(3 + 4, 7) }
func testNotNil() { let value: String? = "Hello" XCTAssertNotNil(value) }
func testThrows() { XCTAssertThrowsError(try someFunctionThatThrows()) }
This program tests simple addition and subtraction using XCTest.
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()
Use XCTAssert functions to check conditions in tests.
Test methods must start with test to be recognized.
Run tests often to catch bugs early.
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.
class MyTests: XCTestCase {
func testSum() {
let result = 2 + 3
XCTAssertEqual(result, 5)
}
}class SampleTests: XCTestCase {
func testMultiply() {
let product = 4 * 5
XCTAssertEqual(product, 20
}
}Pass the test and this pattern moves unknown