Source profileQuality 65/100

affaan-m/ECC/docs/zh-CN/skills/swift-protocol-di-testing/SKILL.md

swift-protocol-di-testing

Use it for testing and engineering tasks; the detail page covers purpose, installation, and practical steps.

Source repository stars
234,327
Declared platforms
0
Static risk flags
0
Last source update
2026-07-27
Source checked
2026-07-28

Decision brief

What it does—and where it fits

通过将外部依赖(文件系统、网络、iCloud)抽象为小型、专注的协议,使 Swift 代码可测试的模式。支持无需 I/O 的确定性测试。

Best for

    Not for

    • Tasks that require unconfirmed production actions or broad system permissions.
    • Environments where the pinned source and install steps cannot be inspected.

    Compatibility matrix

    Platform support, with evidence labels

    PlatformStatusEvidenceWhat to check
    CodexNot declaredNo explicit evidencePortability before use
    Claude CodeNot declaredNo explicit evidencePortability before use
    CursorNot declaredNo explicit evidencePortability before use
    Gemini CLINot declaredNo explicit evidencePortability before use
    Open the compatibility checker

    Installation

    Inspect first. Install second.

    The source command is displayed only when detected. A safe inspection prompt is always available so your agent can explain every action before execution.

    Source-detected install commandSource
    npx skills add https://github.com/affaan-m/ECC --skill "docs/zh-CN/skills/swift-protocol-di-testing"
    Safe inspection promptEditorial

    Inspect the Agent Skill "swift-protocol-di-testing" from https://github.com/affaan-m/ECC/blob/4e973d3eaf92d97f8d2e2d8abb39d8bdc8711b38/docs/zh-CN/skills/swift-protocol-di-testing/SKILL.md at commit 4e973d3eaf92d97f8d2e2d8abb39d8bdc8711b38. List every install step, command, network request, credential, file read/write, external action, and rollback step. Explain whether it fits my task. Do not install or execute anything until I approve.

    Workflow

    What the source asks the agent to do

    1. 01

      何时激活

      编写访问文件系统、网络或外部 API 的 Swift 代码时 需要在未触发真实故障的情况下测试错误处理路径时 构建需要在不同环境(应用、测试、SwiftUI 预览)中工作的模块时 设计支持 Swift 并发(actor、Sendable)的可测试架构时

      编写访问文件系统、网络或外部 API 的 Swift 代码时需要在未触发真实故障的情况下测试错误处理路径时构建需要在不同环境(应用、测试、SwiftUI 预览)中工作的模块时
    2. 02

      核心模式

      Review the “核心模式” section in the pinned source before continuing.

      Review and apply the “核心模式” source section.
    3. 03

      1. 定义小型、专注的协议

      Review the “1. 定义小型、专注的协议” section in the pinned source before continuing.

      Review and apply the “1. 定义小型、专注的协议” source section.
    4. 04

      2. 创建默认(生产)实现

      Review the “2. 创建默认(生产)实现” section in the pinned source before continuing.

      Review and apply the “2. 创建默认(生产)实现” source section.

    Permission review

    Static risk signals and limitations

    No configured static risk pattern was detected

    This is not proof of safety. Runtime behavior, indirect dependencies, and hidden external systems are outside the static scan.

    Evidence record

    Why each signal appears

    EvidenceSourceComputedTestedEditorial
    SignalValueEvidence typeMeaning
    Quality score65/100ComputedDocumentation, specificity, maintenance, and trust rules
    Repository stars234,327SourceRepository attention, not individual Skill quality
    Compatibility0 platformsSourceDeclared in the catalog source record
    Usage guideautomated source guideEditorialGenerated or reviewed according to the visible evidence level

    Pinned source

    Provenance and original SKILL.md

    Repository
    affaan-m/ECC
    Skill path
    docs/zh-CN/skills/swift-protocol-di-testing/SKILL.md
    Commit
    4e973d3eaf92d97f8d2e2d8abb39d8bdc8711b38
    License
    MIT
    Collected
    2026-07-28
    Default branch
    main
    View the original SKILL.md

    基于协议的 Swift 依赖注入测试

    通过将外部依赖(文件系统、网络、iCloud)抽象为小型、专注的协议,使 Swift 代码可测试的模式。支持无需 I/O 的确定性测试。

    何时激活

    • 编写访问文件系统、网络或外部 API 的 Swift 代码时
    • 需要在未触发真实故障的情况下测试错误处理路径时
    • 构建需要在不同环境(应用、测试、SwiftUI 预览)中工作的模块时
    • 设计支持 Swift 并发(actor、Sendable)的可测试架构时

    核心模式

    1. 定义小型、专注的协议

    每个协议仅处理一个外部关注点。

    // File system access
    public protocol FileSystemProviding: Sendable {
        func containerURL(for purpose: Purpose) -> URL?
    }
    
    // File read/write operations
    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
    }
    
    // Bookmark storage (e.g., for sandboxed apps)
    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")
            )
            // Process data...
        }
    }
    

    5. 使用 Swift Testing 编写测试

    import Testing
    
    @Test("Sync manager handles missing container")
    func testMissingContainer() async {
        let mockFileSystem = MockFileSystemProvider(containerURL: nil)
        let manager = SyncManager(fileSystem: mockFileSystem)
    
        await #expect(throws: SyncError.containerNotAvailable) {
            try await manager.sync()
        }
    }
    
    @Test("Sync manager reads data correctly")
    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("Sync manager handles read errors gracefully")
    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、结构化并发)的应用

    Alternatives

    Compare before choosing