[Day 25] 使用 XCTest 來建立單元測試
前言 CSV 資料的讀取與解析,這項功能是 App 的核心之一。然而,隨著專案越來越複雜,我們很可能會在未來的某個時候不小心改動到相關程式碼,或是 CSV 檔案有異動,導致這個功能壞掉。為了確保它能一直穩定運作,我們需要為它建立一道防線——單元測試。 單元測試可以幫助我們驗證一小段程式碼(一個「單元」)的行為是否符合預期。今天,我們將使用 Apple 官方的測試框架 XCTest 來為 RoadDataManager 撰寫測試,確保它在面對正常與異常資料時,都能做出正確的反應。 將 XCTest 加入專案 如果你的專案一開始建立時沒有勾選 Include Tests,我們需要手動將其加入。 首先,在 Xcode 專案導覽器中點擊最上層的專案檔案,進入設定頁面。在「TARGETS」區域點擊左下角的「+」按鈕,選擇新增「Unit Testing Bundle」。你可以為這個測試目標命名,例如 RoadMileLocatorTests,Xcode 便會為你建立好測試所需的環境。 撰寫你的測試案例 建立測試目標後,Xcode 會自動生成一個樣板檔案。雖然可以直接使用,但更好的做法是為特定的類別建立專屬的測試檔案。這樣一來,當 RoadDataManager 的功能需要擴充或修改時,我們就能立刻找到對應的測試案例來進行驗證。 import XCTest final class RoadMileLocatorTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. // Any test you write for XCTest can be annotated as throws and async. // Mark your test throws to produce an unexpected failure when your test encounters an uncaught error. // Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards. } func testPerformanceExample() throws { // This is an example of a performance test case. measure { // Put the code you want to measure the time of here. } } } 這個是由 Xcode 自動產生的單元測試的 Template: ...