top of page

使用 Fastlane 執行 Xcode 測試 - 進階篇 (2/2)

  • 作家相片: Mason Chang
    Mason Chang
  • 1月7日
  • 讀畢需時 2 分鐘

已更新:1月23日

前篇我們知道如何使用 Fastlane 進行測試,但單純只用前一篇的內容是無法用在公司的專案上的,原因如下

  • 模擬器的不穩定性:呼叫既有的模擬器可能因為本機變數影響導致測試結果不穩定。

  • 敏感資料的管理:將 API Key 等敏感信息直接寫在 Fastfile 中,存在安全風險。

  • 測試報告:執行測試後,我們希望能夠生成結構化的測試報告。




建立與刪除模擬器

  • 動態建立模擬器可以確保每次測試環境的乾淨,避免受本機既有模擬器影響。

    • Fastfile 設定範例

default_platform(:ios)

platform :ios do
  lane :run_test do
    runtime     = "com.apple.CoreSimulator.SimRuntime.iOS-18-1"
    device_type = "com.apple.CoreSimulator.SimDeviceType.iPhone-16"
    device_name = "TestDevice"
    
    UI.message("Creating simulator: #{device_name}")
    device_uuid = sh("xcrun simctl create '#{device_name}' '#{device_type}' '#{runtime}'").strip

    begin
      sh("xcrun simctl boot #{device_uuid}")
	
      # 等待模擬器 boot 完
      sleep(10)

      run_tests(
        scheme: "YourScheme",
        destination: "platform=iOS Simulator,id=#{device_uuid}",
        clean: true
      )
    ensure
      UI.message("Deleting simulator: #{device_uuid}")
      sh("xcrun simctl shutdown #{device_uuid}")
      sh("xcrun simctl delete #{device_uuid}")
    end
  end
end
  • 重要參數解析

    • runtime:指定模擬器的運行環境,例如 com.apple.CoreSimulator.SimRuntime.iOS-18-1 代表 iOS 18.1 的模擬環境。可以使用 xcrun simctl list runtimes 查看可用的 runtime。

    • device_type:模擬器的設備類型,例如 com.apple.CoreSimulator.SimDeviceType.iPhone-16 代表 iPhone 14。可用的設備類型可以通過 xcrun simctl list devicetypes 查看。

    • device_name:為模擬器指定一個可識別的名稱,便於管理和調試,例如 TestDevice。



使用 dotenv 管理環境變數

  • 敏感資料如 API Key 或 Apple ID 應存儲於安全的環境變數中,而非直接寫入 Fastfile。

    • 設置步驟

      • 安裝 dotenv

gem install dotenv
  • 創建 .env 文件

API_KEY=your_api_key 
APPLE_ID=your_apple_id 
PASSWORD=your_password
  • 在 Fastfile 中載入 dotenv,在 Fastfile 內容補上以下內容

require 'dotenv' 
Dotenv.load  

# 測試確實有讀取到環境變數
lane :example do
	UI.message("Using API_KEY: #{ENV['API_KEY']}")
end


使用 Slather 生成測試覆蓋率報告

測試覆蓋率報告能提供測試完整性的量化指標,幫助團隊分析測試的有效性。

  • 配置步驟

    • 安裝 Slather

gem install slather
  • 初始化 Slather

slather setup YourApp.xcodeproj
  • 生成覆蓋率報告

slather coverage --junit --output-directory ./coverage_reports YourApp.xcodeproj
  • 在 Fastfile 中整合

lane :generate_coverage do   
	scan(scheme: "YourScheme",
      	 clean: true)  
  
	slather(build_directory: "./build",
     		output_directory: "./coverage_reports",
	     	coverage_service: "junit")    
	UI.message("JUnit coverage report generated at ./coverage_reports") 
end

Summary

通過動態模擬器管理、dotenv 與 Slather 的應用,我們解決了測試環境不穩定、敏感資料管理與測試報告生成的需求,使自動化測試流程更加安全、可靠與高效。


 
 
 

留言


follow me
  • Facebook
  • LinkedIn

Thanks for submitting!

IMG_5625_edited_edited.jpg
Mason
Small habits, repeated daily, lead to extraordinary results.
bottom of page