[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6G2CZJQPYPFH2XFE57XFCVR":3,"skill-same:01M6G2CZJQPYPFH2XFE57XFCVR":58},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":23,"publishedAt":29,"linkOnly":30,"markdownContent":31,"markdownBody":32,"frontMatter":33,"refName":35,"commitSha":36,"skillDirectory":37,"forksCount":38,"repositoryHtmlUrl":39,"repositoryHomepageUrl":6,"ownerHtmlUrl":40,"ownerBlogUrl":41,"ownerDescription":42,"updatedAt":43,"install":44,"resources":57},"01M6G2CZJQPYPFH2XFE57XFCVR","swift-protocol-di-testing",null,"基于协议的依赖注入，用于可测试的Swift代码——使用聚焦协议和Swift Testing模拟文件系统、网络和外部API。","oabdelmaksoud\u002FAgention","oabdelmaksoud","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F50699149?v=4","01M6D5CVVN778ZCDP1WHS816SP","Omar Abdelmaksoud","01M6D8A4TE76V3DCSH3D94VG1V",2,"MIT","https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FAgention\u002Fblob\u002Fmain\u002Fupstream-sync\u002Fwork\u002Fecc\u002Fdocs\u002Fzh-CN\u002Fskills\u002Fswift-protocol-di-testing\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000008","测试与质量","SCENARIO","使用场景",[24,25,26,27,28],"testing","swift","protocol","swift protocol di testing","文件","2026-11-10 10:12:30",false,"---\nname: swift-protocol-di-testing\ndescription: 基于协议的依赖注入，用于可测试的Swift代码——使用聚焦协议和Swift Testing模拟文件系统、网络和外部API。\norigin: ECC\n---\n\n# 基于协议的 Swift 依赖注入测试\n\n通过将外部依赖（文件系统、网络、iCloud）抽象为小型、专注的协议，使 Swift 代码可测试的模式。支持无需 I\u002FO 的确定性测试。\n\n## 何时激活\n\n* 编写访问文件系统、网络或外部 API 的 Swift 代码时\n* 需要在未触发真实故障的情况下测试错误处理路径时\n* 构建需要在不同环境（应用、测试、SwiftUI 预览）中工作的模块时\n* 设计支持 Swift 并发（actor、Sendable）的可测试架构时\n\n## 核心模式\n\n### 1. 定义小型、专注的协议\n\n每个协议仅处理一个外部关注点。\n\n```swift\n\u002F\u002F File system access\npublic protocol FileSystemProviding: Sendable {\n    func containerURL(for purpose: Purpose) -> URL?\n}\n\n\u002F\u002F File read\u002Fwrite operations\npublic protocol FileAccessorProviding: Sendable {\n    func read(from url: URL) throws -> Data\n    func write(_ data: Data, to url: URL) throws\n    func fileExists(at url: URL) -> Bool\n}\n\n\u002F\u002F Bookmark storage (e.g., for sandboxed apps)\npublic protocol BookmarkStorageProviding: Sendable {\n    func saveBookmark(_ data: Data, for key: String) throws\n    func loadBookmark(for key: String) throws -> Data?\n}\n```\n\n### 2. 创建默认（生产）实现\n\n```swift\npublic struct DefaultFileSystemProvider: FileSystemProviding {\n    public init() {}\n\n    public func containerURL(for purpose: Purpose) -> URL? {\n        FileManager.default.url(forUbiquityContainerIdentifier: nil)\n    }\n}\n\npublic struct DefaultFileAccessor: FileAccessorProviding {\n    public init() {}\n\n    public func read(from url: URL) throws -> Data {\n        try Data(contentsOf: url)\n    }\n\n    public func write(_ data: Data, to url: URL) throws {\n        try data.write(to: url, options: .atomic)\n    }\n\n    public func fileExists(at url: URL) -> Bool {\n        FileManager.default.fileExists(atPath: url.path)\n    }\n}\n```\n\n### 3. 创建用于测试的模拟实现\n\n```swift\npublic final class MockFileAccessor: FileAccessorProviding, @unchecked Sendable {\n    public var files: [URL: Data] = [:]\n    public var readError: Error?\n    public var writeError: Error?\n\n    public init() {}\n\n    public func read(from url: URL) throws -> Data {\n        if let error = readError { throw error }\n        guard let data = files[url] else {\n            throw CocoaError(.fileReadNoSuchFile)\n        }\n        return data\n    }\n\n    public func write(_ data: Data, to url: URL) throws {\n        if let error = writeError { throw error }\n        files[url] = data\n    }\n\n    public func fileExists(at url: URL) -> Bool {\n        files[url] != nil\n    }\n}\n```\n\n### 4. 使用默认参数注入依赖项\n\n生产代码使用默认值；测试注入模拟对象。\n\n```swift\npublic actor SyncManager {\n    private let fileSystem: FileSystemProviding\n    private let fileAccessor: FileAccessorProviding\n\n    public init(\n        fileSystem: FileSystemProviding = DefaultFileSystemProvider(),\n        fileAccessor: FileAccessorProviding = DefaultFileAccessor()\n    ) {\n        self.fileSystem = fileSystem\n        self.fileAccessor = fileAccessor\n    }\n\n    public func sync() async throws {\n        guard let containerURL = fileSystem.containerURL(for: .sync) else {\n            throw SyncError.containerNotAvailable\n        }\n        let data = try fileAccessor.read(\n            from: containerURL.appendingPathComponent(\"data.json\")\n        )\n        \u002F\u002F Process data...\n    }\n}\n```\n\n### 5. 使用 Swift Testing 编写测试\n\n```swift\nimport Testing\n\n@Test(\"Sync manager handles missing container\")\nfunc testMissingContainer() async {\n    let mockFileSystem = MockFileSystemProvider(containerURL: nil)\n    let manager = SyncManager(fileSystem: mockFileSystem)\n\n    await #expect(throws: SyncError.containerNotAvailable) {\n        try await manager.sync()\n    }\n}\n\n@Test(\"Sync manager reads data correctly\")\nfunc testReadData() async throws {\n    let mockFileAccessor = MockFileAccessor()\n    mockFileAccessor.files[testURL] = testData\n\n    let manager = SyncManager(fileAccessor: mockFileAccessor)\n    let result = try await manager.loadData()\n\n    #expect(result == expectedData)\n}\n\n@Test(\"Sync manager handles read errors gracefully\")\nfunc testReadError() async {\n    let mockFileAccessor = MockFileAccessor()\n    mockFileAccessor.readError = CocoaError(.fileReadCorruptFile)\n\n    let manager = SyncManager(fileAccessor: mockFileAccessor)\n\n    await #expect(throws: SyncError.self) {\n        try await manager.sync()\n    }\n}\n```\n\n## 最佳实践\n\n* **单一职责**：每个协议应处理一个关注点——不要创建包含许多方法的“上帝协议”\n* **Sendable 一致性**：当协议跨 actor 边界使用时需要\n* **默认参数**：让生产代码默认使用真实实现；只有测试需要指定模拟对象\n* **错误模拟**：设计具有可配置错误属性的模拟对象以测试故障路径\n* **仅模拟边界**：模拟外部依赖（文件系统、网络、API），而非内部类型\n\n## 需要避免的反模式\n\n* 创建覆盖所有外部访问的单个大型协议\n* 模拟没有外部依赖的内部类型\n* 使用 `#if DEBUG` 条件语句代替适当的依赖注入\n* 与 actor 一起使用时忘记 `Sendable` 一致性\n* 过度设计：如果一个类型没有外部依赖，则不需要协议\n\n## 何时使用\n\n* 任何触及文件系统、网络或外部 API 的 Swift 代码\n* 测试在真实环境中难以触发的错误处理路径时\n* 构建需要在应用、测试和 SwiftUI 预览上下文中工作的模块时\n* 需要使用可测试架构的、采用 Swift 并发（actor、结构化并发）的应用\n","# 基于协议的 Swift 依赖注入测试\n\n通过将外部依赖（文件系统、网络、iCloud）抽象为小型、专注的协议，使 Swift 代码可测试的模式。支持无需 I\u002FO 的确定性测试。\n\n## 何时激活\n\n* 编写访问文件系统、网络或外部 API 的 Swift 代码时\n* 需要在未触发真实故障的情况下测试错误处理路径时\n* 构建需要在不同环境（应用、测试、SwiftUI 预览）中工作的模块时\n* 设计支持 Swift 并发（actor、Sendable）的可测试架构时\n\n## 核心模式\n\n### 1. 定义小型、专注的协议\n\n每个协议仅处理一个外部关注点。\n\n```swift\n\u002F\u002F File system access\npublic protocol FileSystemProviding: Sendable {\n    func containerURL(for purpose: Purpose) -> URL?\n}\n\n\u002F\u002F File read\u002Fwrite operations\npublic protocol FileAccessorProviding: Sendable {\n    func read(from url: URL) throws -> Data\n    func write(_ data: Data, to url: URL) throws\n    func fileExists(at url: URL) -> Bool\n}\n\n\u002F\u002F Bookmark storage (e.g., for sandboxed apps)\npublic protocol BookmarkStorageProviding: Sendable {\n    func saveBookmark(_ data: Data, for key: String) throws\n    func loadBookmark(for key: String) throws -> Data?\n}\n```\n\n### 2. 创建默认（生产）实现\n\n```swift\npublic struct DefaultFileSystemProvider: FileSystemProviding {\n    public init() {}\n\n    public func containerURL(for purpose: Purpose) -> URL? {\n        FileManager.default.url(forUbiquityContainerIdentifier: nil)\n    }\n}\n\npublic struct DefaultFileAccessor: FileAccessorProviding {\n    public init() {}\n\n    public func read(from url: URL) throws -> Data {\n        try Data(contentsOf: url)\n    }\n\n    public func write(_ data: Data, to url: URL) throws {\n        try data.write(to: url, options: .atomic)\n    }\n\n    public func fileExists(at url: URL) -> Bool {\n        FileManager.default.fileExists(atPath: url.path)\n    }\n}\n```\n\n### 3. 创建用于测试的模拟实现\n\n```swift\npublic final class MockFileAccessor: FileAccessorProviding, @unchecked Sendable {\n    public var files: [URL: Data] = [:]\n    public var readError: Error?\n    public var writeError: Error?\n\n    public init() {}\n\n    public func read(from url: URL) throws -> Data {\n        if let error = readError { throw error }\n        guard let data = files[url] else {\n            throw CocoaError(.fileReadNoSuchFile)\n        }\n        return data\n    }\n\n    public func write(_ data: Data, to url: URL) throws {\n        if let error = writeError { throw error }\n        files[url] = data\n    }\n\n    public func fileExists(at url: URL) -> Bool {\n        files[url] != nil\n    }\n}\n```\n\n### 4. 使用默认参数注入依赖项\n\n生产代码使用默认值；测试注入模拟对象。\n\n```swift\npublic actor SyncManager {\n    private let fileSystem: FileSystemProviding\n    private let fileAccessor: FileAccessorProviding\n\n    public init(\n        fileSystem: FileSystemProviding = DefaultFileSystemProvider(),\n        fileAccessor: FileAccessorProviding = DefaultFileAccessor()\n    ) {\n        self.fileSystem = fileSystem\n        self.fileAccessor = fileAccessor\n    }\n\n    public func sync() async throws {\n        guard let containerURL = fileSystem.containerURL(for: .sync) else {\n            throw SyncError.containerNotAvailable\n        }\n        let data = try fileAccessor.read(\n            from: containerURL.appendingPathComponent(\"data.json\")\n        )\n        \u002F\u002F Process data...\n    }\n}\n```\n\n### 5. 使用 Swift Testing 编写测试\n\n```swift\nimport Testing\n\n@Test(\"Sync manager handles missing container\")\nfunc testMissingContainer() async {\n    let mockFileSystem = MockFileSystemProvider(containerURL: nil)\n    let manager = SyncManager(fileSystem: mockFileSystem)\n\n    await #expect(throws: SyncError.containerNotAvailable) {\n        try await manager.sync()\n    }\n}\n\n@Test(\"Sync manager reads data correctly\")\nfunc testReadData() async throws {\n    let mockFileAccessor = MockFileAccessor()\n    mockFileAccessor.files[testURL] = testData\n\n    let manager = SyncManager(fileAccessor: mockFileAccessor)\n    let result = try await manager.loadData()\n\n    #expect(result == expectedData)\n}\n\n@Test(\"Sync manager handles read errors gracefully\")\nfunc testReadError() async {\n    let mockFileAccessor = MockFileAccessor()\n    mockFileAccessor.readError = CocoaError(.fileReadCorruptFile)\n\n    let manager = SyncManager(fileAccessor: mockFileAccessor)\n\n    await #expect(throws: SyncError.self) {\n        try await manager.sync()\n    }\n}\n```\n\n## 最佳实践\n\n* **单一职责**：每个协议应处理一个关注点——不要创建包含许多方法的“上帝协议”\n* **Sendable 一致性**：当协议跨 actor 边界使用时需要\n* **默认参数**：让生产代码默认使用真实实现；只有测试需要指定模拟对象\n* **错误模拟**：设计具有可配置错误属性的模拟对象以测试故障路径\n* **仅模拟边界**：模拟外部依赖（文件系统、网络、API），而非内部类型\n\n## 需要避免的反模式\n\n* 创建覆盖所有外部访问的单个大型协议\n* 模拟没有外部依赖的内部类型\n* 使用 `#if DEBUG` 条件语句代替适当的依赖注入\n* 与 actor 一起使用时忘记 `Sendable` 一致性\n* 过度设计：如果一个类型没有外部依赖，则不需要协议\n\n## 何时使用\n\n* 任何触及文件系统、网络或外部 API 的 Swift 代码\n* 测试在真实环境中难以触发的错误处理路径时\n* 构建需要在应用、测试和 SwiftUI 预览上下文中工作的模块时\n* 需要使用可测试架构的、采用 Swift 并发（actor、结构化并发）的应用\n",{"name":5,"origin":34,"description":7},"ECC","main","a318f48de3c5718e8ea2e9f6fae7790e8a759e85","upstream-sync\u002Fwork\u002Fecc\u002Fdocs\u002Fzh-CN\u002Fskills\u002Fswift-protocol-di-testing",0,"https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FAgention","https:\u002F\u002Fgithub.com\u002Foabdelmaksoud","https:\u002F\u002Fwww.linkedin.com\u002Fin\u002Fo-abdelmaksoud\u002F","Full-Stack Engineer | AI Systems Architect | Building autonomous multi-agent systems","2026-03-08 21:23:03",{"source":8,"skillName":5,"commands":45,"prompt":55,"zipAvailable":56},[46,49,52],{"tool":47,"command":48},"npx","npx skills add oabdelmaksoud\u002FAgention --skill swift-protocol-di-testing",{"tool":50,"command":51},"bunx","bunx skills add oabdelmaksoud\u002FAgention --skill swift-protocol-di-testing",{"tool":53,"command":54},"pnpm","pnpm dlx skills add oabdelmaksoud\u002FAgention --skill swift-protocol-di-testing","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FAgention\u002Fblob\u002Fmain\u002Fupstream-sync\u002Fwork\u002Fecc\u002Fdocs\u002Fzh-CN\u002Fskills\u002Fswift-protocol-di-testing\u002FSKILL.md",true,[],[59,81,95,126,152,167],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":68,"publishedAt":29},"01M6G2QFCBNBYAJF2KTK85G9A6","visa-doc-translate","Translate visa application documents (images) to English and create a bilingual PDF with original and translation","https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FAgention\u002Fblob\u002Fmain\u002Fupstream-sync\u002Fwork\u002Fecc\u002Fskills\u002Fvisa-doc-translate\u002FSKILL.md",[65],{"categoryNo":66,"categoryName":67,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000002","文档处理",[69,70,71,72,73,74,75,76,77,78,79,80],"translate","doc","visa doc translate","bilingual","with","english","application","PDF","translation","documents","create","images",{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":29},"01M6G2QB09TSK6BY4ME5X20EVQ","verification-loop","A comprehensive verification system for Claude Code sessions.","https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FAgention\u002Fblob\u002Fmain\u002Fupstream-sync\u002Fwork\u002Fecc\u002Fskills\u002Fverification-loop\u002FSKILL.md",[],[88,89,90,91,92,93,94],"verification","loop","verification loop","sessions","code","claude code sessions","system",{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":110,"publishedAt":29},"01M6G2Q6V2F7G03VAAF27FXPJR","tdd-workflow","Use this skill when writing new features, fixing bugs, or refactoring code. Enforces test-driven development with 80%+ coverage including unit, integration, and E2E tests.","https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FAgention\u002Fblob\u002Fmain\u002Fupstream-sync\u002Fwork\u002Fecc\u002Fskills\u002Ftdd-workflow\u002FSKILL.md",[101,102,105],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":103,"categoryName":104,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":106,"categoryName":107,"taxonomyType":108,"taxonomyTypeDesc":109},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[111,112,113,114,115,116,117,118,119,92,120,121,122,123,73,124,125],"workflow","tdd","tdd workflow","use","unit","coverage","refactoring","e2e","integration","development","e2e tests","tests","driven","test","writing",{"skillNo":127,"name":128,"nameZh":6,"description":129,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":130,"categories":131,"keywords":132,"publishedAt":29},"01M6G2Q359YJRWAR2PFCEQAXF3","swiftui-patterns","SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS\u002FmacOS UI best practices.","https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FAgention\u002Fblob\u002Fmain\u002Fupstream-sync\u002Fwork\u002Fecc\u002Fskills\u002Fswiftui-patterns\u002FSKILL.md",[],[133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,73],"patterns","swiftui","swiftui patterns","architecture","macos","performance","state management","best practices","state","ui","Optimization","ios","architecture patterns","Composition","performance optimization","view","management","swiftui architecture","navigation",{"skillNo":153,"name":5,"nameZh":6,"description":154,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":155,"categories":156,"keywords":158,"publishedAt":29},"01M6G2PY8B2FWZTWPZ84H83Y7C","Protocol-based dependency injection for testable Swift code — mock file system, network, and external APIs using focused protocols and Swift Testing.","https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FAgention\u002Fblob\u002Fmain\u002Fupstream-sync\u002Fwork\u002Fecc\u002Fskills\u002Fswift-protocol-di-testing\u002FSKILL.md",[157],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[27,26,25,24,92,159,160,161,162,94,163,164,165,166],"protocols","file","network","injection","dependency","swift testing","dependency injection","mock",{"skillNo":168,"name":169,"nameZh":6,"description":170,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":171,"categories":172,"keywords":173,"publishedAt":29},"01M6G2PSCN2GXV9FFZDRRRWVB6","swift-concurrency-6-2","Swift 6.2 Approachable Concurrency — single-threaded by default, @concurrent for explicit background offloading, isolated conformances for main actor types.","https:\u002F\u002Fgithub.com\u002Foabdelmaksoud\u002FAgention\u002Fblob\u002Fmain\u002Fupstream-sync\u002Fwork\u002Fecc\u002Fskills\u002Fswift-concurrency-6-2\u002FSKILL.md",[],[174,175,176,25,177,35,178],"concurrency","swift concurrency","swift concurrency 6 2","default","types"]