static var allTests = [ testCase(CalculatorTests.testAddition), testCase(CalculatorTests.testSubtraction) ]
測試非同步方法
let expectation = XCTestExpectation(description: "HTTP request") expectation.fulfill() wait(for: [expectation], timeout: 5.0)
import XCTest @testable import ARDemo //建立CalculatorTests類,繼承自XCTestCase class CalculatorTests: XCTestCase { var calculator: Calculator! //測試開始前,初始化要使用的環境變數 override func setUp() { super.setUp() calculator = Calculator() } //測試結束後,清理使用的環境變數 override func tearDown() { super.tearDown() calculator = nil } //要控制測試用例的執行順序 //1.可以通過test+101這種形式,順序會根據test後面的數位,先小,後大的順序進行執行 func test101Addition() { let result = calculator.add(2, 3) XCTAssertEqual(result, 5, "Addition of 2 and 3 should be 5") } func test102Addition() { let result = calculator.add(2, 3) XCTAssertEqual(result, 5, "Addition of 2 and 3 should be 5") } func test103Addition() { let result = calculator.add(2, 3) XCTAssertEqual(result, 5, "Addition of 2 and 3 should be 5") } //2.使用測試用例組的形式,執行順序會按照組中的順序,由上到下進行執行 func testAddition() { let result = calculator.add(2, 3) XCTAssertEqual(result, 5, "Addition result is incorrect") } func testSubtraction() { let result = calculator.subtract(5, 2) XCTAssertEqual(result, 3, "Subtraction result is incorrect") } //靜態變數allTests中放置排序後的測試用例 static var allTests = [ testCase(CalculatorTests.testAddition), testCase(CalculatorTests.testSubtraction) ] //測試非同步方法 func testAsyncHTTPRequest() { let expectation = XCTestExpectation(description: "HTTP request") // 呼叫非同步HTTP請求方法 asyncHTTPRequest { response in // 處理回撥結果 XCTAssertTrue(response.success) expectation.fulfill() } // 等待非同步操作完成 wait(for: [expectation], timeout: 5.0) } //測試功能的執行效能 func testPerformance() { measure([.wallClockTime, .userTime]) { // 執行需要測試效能的程式碼塊 } } } class Calculator { func add(_ a: Int, _ b: Int) -> Int { return a + b } func subtract(_ a: Int, _ b: Int) -> Int { return a - b } }