Swift 基於協定的依賴注入測試 是做什麼的?
透過將外部依賴(檔案系統、網路、iCloud)抽象成小而專注的協定,讓 Swift 程式碼可測試。無需實際 I/O 即可進行確定性測試。
何時啟用
- 撰寫存取檔案系統、網路或外部 API 的 Swift 程式碼
- 需要測試錯誤處理路徑,但不想觸發真實錯誤
- 建構需跨環境(App、測試、SwiftUI 預覽)運作的模組
- 設計支援 Swift Concurrency(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(