Swift 基於協定的依賴注入測試 是做什麼的?
透過將外部依賴(檔案系統、網路、iCloud)抽象成小型、聚焦的協定,讓 Swift 程式碼可測試。此模式可實現無 I/O 的確定性測試。
何時啟用
- 撰寫存取檔案系統、網路或外部 API 的 Swift 程式碼
- 需要測試錯誤處理路徑,而不觸發實際錯誤
- 建構可跨環境(應用、測試、SwiftUI 預覽)運作的模組
- 使用 Swift 並行(actor、Sendable)設計可測試的架構
核心模式
1. 定義小型、聚焦的協定
每個協定只處理一個外部關注點。
// 檔案系統存取
public protocol FileSystemProviding: Sendable {
func containerURL(for purpose: Purpose) -> URL?
}
// 檔案讀寫操作
public protocol FileAccessorProviding: Sendable {
func read(from url: URL) throws -> Data
func write(_ data: Data, to url: URL) throws
func fileExists(at url: URL) -> Bool
}
// 書籤儲存(例如沙盒應用)
public protocol BookmarkStorageProviding: Sendable {
func saveBookmark(_ data: Data, for key: String) throws
func loadBookmark(for key: String) throws -> Data?
}
2. 建立預設(生產環境)實作
public struct DefaultFileSystemProvider: FileSystemProviding {
public init() {}
public func containerURL(for purpose: Purpose) -> URL? {
FileManager.default.url(forUbiquityContainerIdentifier: nil)
}
}
public struct DefaultFileAccessor: FileAccessorProviding {
public init() {}
public func read(from url: URL) throws -> Data {
try Data(contentsOf: url)
}
public func write(_ data: Data, to url: URL) throws {
try data.write(to: url, options: .atomic)
}
public func fileExists(at url: URL) -> Bool {
FileManager.default.fileExists(atPath: url.path)
}
}
3. 建立測試用的模擬實作
public final class MockFileAccessor: FileAccessorProviding, @unchecked Sendable {
public var files: [URL: Data] = [:]
public var readError: Error?
public var writeError: Error?
public init() {}
public func read(from url: URL) throws -> Data {
if let error = readError { throw error }
guard let data = files[url] else {
throw CocoaError(.fileReadNoSuchFile)
}
return data
}
public func write(_ data: Data, to url: URL) throws {
if let error = writeError { throw error }
files[url] = data
}
public func fileExists(at url: URL) -> Bool {
files[url] != nil
}
}
4. 使用預設參數注入依賴
生產程式碼使用預設實作;測試時注入模擬物件。
public actor SyncManager {
private let fileSystem: FileSystemProviding
private let fileAccessor: FileAccessorProviding
public init(
fileSystem: FileSystemProviding = DefaultFileSystemProvider(),
fileAccessor: FileAccessorProviding = DefaultFileAccessor()
) {
self.fileSystem = fileSystem
self.fileAccessor = fileAccessor
}
public func sync() async throws {
guard let containerURL = fileSystem.containerURL(for: .sync) else {
throw SyncError.containerNotAvailable
}
let data = try fileAccessor.read(
from: containerURL.appendingPathComponent("data.json")
)
// 處理資料...
}
}
5. 使用 Swift Testing 撰寫測試
import Testing
@Test("同步管理器處理遺失容器")
func testMissingContainer() async {
let mockFileSystem = MockFileSystemProvider(containerURL: nil)
let manager = SyncManager(fileSystem: mockFileSystem)
await #expect(throws: SyncError.containerNotAvailable) {
try await manager.sync()
}
}
@Test("同步管理器正確讀取資料")
func testReadData() async throws {
let mockFileAccessor = MockFileAccessor()
mockFileAccessor.files[testURL] = testData
let manager = SyncManager(fileAccessor: mockFileAccessor)
let result = try await manager.loadData()
#expect(result == expectedData)
}
@Test("同步管理器優雅處理讀取錯誤")
func testReadError() async {
let mockFileAccessor = MockFileAccessor()
mockFileAccessor.readError = CocoaError(.fileReadCorruptFile)
let manager = SyncManager(fileAccessor: mockFileAccessor)
await #expect(throws: SyncError.self) {
try await manager.sync()
}
}
最佳實踐
- 單一職責:每個協定只處理一個關注點——不要建立包含許多方法的「巨型協定」
- Sendable 符合性:當協定跨 actor 邊界使用時必須實作
- 預設參數:讓生產程式碼預設使用真實實作;只有測試才需要指定模擬物件
- 錯誤模擬:設計模擬物件時包含可設定的錯誤屬性,以測試失敗路徑
- 僅模擬邊界:模擬外部依賴(檔案系統、網路、API),而不是內部型別
應避免的反模式
- 建立一個單一的大型協定涵蓋所有外部存取
- 模擬沒有外部依賴的內部型別
- 使用
#if DEBUG條件編譯而不是正確的依賴注入 - 在與 actor 一起使用時忘記
Sendable符合性 - 過度設計:如果一個型別沒有外部依賴,就不需要協定
使用時機
- 任何觸及檔案系統、網路或外部 API 的 Swift 程式碼
- 測試在真實環境中難以觸發的錯誤處理路徑
- 建構需要在應用、測試和 SwiftUI 預覽環境中運作的模組
- 使用 Swift 並行(actor、結構化並行)且需要可測試架構的應用