swift-protocol-di-testing

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

Content Preview
---
name: swift-protocol-di-testing
description: 基于协议的依赖注入,用于可测试的Swift代码——使用聚焦协议和Swift Testing模拟文件系统、网络和外部API。
origin: ECC
---

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

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

## 何时激活

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

## 核心模式

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

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

```swift
// File system access
public protocol FileSystemProviding: Sendable {
    func co
How to Use

Recommended: Install to project (local)

mkdir -p .claude/skills
curl -o .claude/skills/swift-protocol-di-testing.md \
  https://raw.githubusercontent.com/affaan-m/everything-claude-code/main/docs/zh-CN/skills/swift-protocol-di-testing/SKILL.md

Skill is scoped to this project only. Add .claude/skills/ to your .gitignoreif you don't want to commit it.

Alternative: Clone full repo

git clone https://github.com/affaan-m/everything-claude-code

Then reference at docs/zh-CN/skills/swift-protocol-di-testing/SKILL.md

Related Skills