affaan-m/ECC

swift-protocol-di-testing

基于协议的依赖注入,用于可测试的Swift代码——使用聚焦协议和Swift Testing模拟文件系统、网络和外部API。

65Collecting
See how to use itView GitHub source
npx skills add https://github.com/affaan-m/ECC --skill "docs/zh-CN/skills/swift-protocol-di-testing"
Automated source guide

Source checked Jul 28, 2026·Refresh due Oct 26, 2026

Reorganized from the pinned upstream SKILL.md

Turn swift-protocol-di-testing's source instructions into a guide you can follow

According to the pinned SKILL.md from affaan-m/ECC: 通过将外部依赖(文件系统、网络、iCloud)抽象为小型、专注的协议,使 Swift 代码可测试的模式。支持无需 I/O 的确定性测试。

npx skills add https://github.com/affaan-m/ECC --skill "docs/zh-CN/skills/swift-protocol-di-testing"
Check the pinned source

Best fit

  • 基于协议的依赖注入,用于可测试的Swift代码——使用聚焦协议和Swift Testing模拟文件系统、网络和外部API。

Bring this context

  • A concrete task that matches the documented purpose of swift-protocol-di-testing.
  • The files, examples, or context the task depends on.
  • Your constraints, target environment, and definition of done.

Expected outputs

  • A result that follows the pinned swift-protocol-di-testing instructions.
  • A concise record of assumptions, inputs used, and unresolved questions.
  • A final check against the source workflow and relevant permission signals.

Key source sections

Read swift-protocol-di-testing through these 5 source sections

Sections are extracted automatically from the pinned SKILL.md and link back to the source.

01

何时激活

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

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

核心模式

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

SKILL.md · 核心模式
Review and apply the “核心模式” source section.
03

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

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

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

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

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

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

3. 创建用于测试的模拟实现

Review the “3. 创建用于测试的模拟实现” section in the pinned source before continuing.

SKILL.md · 3. 创建用于测试的模拟实现
Review and apply the “3. 创建用于测试的模拟实现” source section.

SkillSignal prompt templates

Provide the task, context, and acceptance criteria

These prompts were written by SkillSignal from the source structure; they are not upstream text.

Task-start prompt

Confirm source fit, inputs, and outputs before acting.

Use swift-protocol-di-testing to help me with: [specific task]. Context: [files, data, or background]. Constraints: [environment, scope, and prohibited actions]. Before acting, check the pinned SKILL.md and explain which sections apply, what inputs are still missing, and what you will deliver.

Source-guided execution

Make the Agent explicitly follow the key extracted sections.

Apply the pinned swift-protocol-di-testing source to [task]. Pay particular attention to these source sections: “何时激活”, “核心模式”, “1. 定义小型、专注的协议”, “2. 创建默认(生产)实现”, “3. 创建用于测试的模拟实现”. Preserve the important decision at each step. Mark facts not covered by the source as “needs confirmation” instead of inventing them. Then verify the result against my acceptance criteria: [criteria].

Result-review prompt

Check omissions, permissions, and source drift before delivery.

Review the current swift-protocol-di-testing result: (1) does it satisfy the original task; (2) were any applicable steps or limits in the pinned SKILL.md missed; (3) did it perform any unauthorized file, command, network, or data action; and (4) which conclusions remain unverified? List issues first, then fix only what the source or user authorization supports.

Output checklist

Verify each item before delivery

The task matches the purpose documented in the SKILL.md.

The source section “何时激活” has been checked.

The source section “核心模式” has been checked.

The source section “1. 定义小型、专注的协议” has been checked.

The source section “2. 创建默认(生产)实现” has been checked.

Inputs, constraints, and acceptance criteria are explicit.

Unverified facts, compatibility, and outcome claims are clearly marked.

Any file, command, network, or data action has been reviewed.

Choose a different workflow

When another Skill is the better fit

FAQ

What does swift-protocol-di-testing do?

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

How do I start using swift-protocol-di-testing?

The catalog detected this source-specific install command: npx skills add https://github.com/affaan-m/ECC --skill "docs/zh-CN/skills/swift-protocol-di-testing". Inspect the command and pinned source before running it.

Which Agent platforms does it declare?

No dedicated Agent platform is declared in the pinned source record.

Repository stars
234,327
Repository forks
35,711
Quality
65/100
Source repository last pushed

Quality breakdown

Based on traceable docs and repository signals; stars are not treated as quality.

65/100
Documentation22/30
Specificity11/25
Maintenance20/20
Trust signals12/25

Compare before choosing

Related Agent Skills and source variants

These links are selected from shared tasks, functions, stacks, platforms, and same-name variants. Compare the source owner, documentation, permissions, and maintenance signals.

View original Skill.mdThis page is parsed directly from the repository SKILL.md without editorial rewriting. Collected: Jul 28, 2026 · about 1 min

基于协议的 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、结构化并发)的应用
Source repo
affaan-m/ECC
Skill path
docs/zh-CN/skills/swift-protocol-di-testing/SKILL.md
Commit SHA
4e973d3eaf92
Repository license
MIT
Data collected