swift-protocol-di-testing
Skill2k starsChanged 9 months agoMITView on GitHub
基于协议的依赖注入(Protocol-based Dependency Injection),通过精简的协议和 Swift 测试框架(Swift Testing)来模拟文件系统、网络和外部 API,编写可测试的 Swift 代码。
10 other projects use a version of this, 10 of them edited.
Trending
More talk lately.thin dataabout the whole repository
Most recently taken up by
- templetongroup/radiantedited, first seen Sep 17, 2026
- SamuelNDCE/claude-super-skill-libraryedited, first seen Aug 1, 2026
- Jamkris/everything-gemini-codeedited, first seen Apr 27, 2026
- loulanyue/awesome-claude-notesedited, first seen Mar 24, 2026
- Cyvid7-Darus10/claude-code-configedited, first seen Mar 24, 2026
- mryeastcode/ClaudeCodeedited, first seen Mar 20, 2026
Who's talking about xu-xiang/everything-claude-code-zh
The biggest 1 of 1 mention linking to the repository that our crawl found. Each line is their own headline.
Used with
Projects with it also use kotlin-testing, nuxt4-patterns and 10 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
tpavanipradeepSkillkotlin-testing
Kotlin testing patterns with Kotest, MockK, coroutine testing, property-based testing, and Kover coverage. Follows TDD methodology with idiomatic Kotlin practices.
Also in 4 projects that use this
mryeastcodeSkillnuxt4-patterns
Nuxt 4 app patterns for hydration safety, performance, route rules, lazy loading, and SSR-safe data fetching with useFetch and useAsyncData.
Also in 3 projects that use this
tpavanipradeepSkilllaravel-verification
Verification loop for Laravel projects: env checks, linting, static analysis, tests with coverage, security scans, and deployment readiness.
Also in 3 projects that use this
mryeastcodeSkillsanta-method
Multi-agent adversarial verification with convergence loop. Two independent review agents must both pass before output ships.
Also in 3 projects that use this
Jonathan0823Skillrust-patterns
Rust patterns, ownership best practices, and production-ready code guidelines
Also in 4 projects that use this
CodeWithBehnamSkillx-api
X/Twitter API integration for posting tweets, threads, reading timelines, search, and analytics. Covers OAuth auth patterns, rate limits, and platform-native content posting. Use when the user wants to interact with X programmatically.
Also in 3 projects that use this
- +5 more from tpavanipradeep
- +1 more from mryeastcode
Other versions10 projects use a version of this.
Word for word · 0
None found.
Edited · 10
- loulanyue/awesome-claude-notes★ 27246% same
- tpavanipradeep/everything-claude-code★ 13446% same
- templetongroup/radiant★ 11345% same
- Jamkris/everything-gemini-code★ 8746% same
- Infopibe/everything-claude-code★ 846% same
- Cyvid7-Darus10/claude-code-config★ 246% same
- ashutoshrathi0909-oss/everything-claude-code★ 146% same
- royaluniondesign-sys/claude-os★ 146% same
- SamuelNDCE/claude-super-skill-library★ 146% same
- mryeastcode/ClaudeCode★ 046% same
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository114 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .codex/AGENTS.mdAGENTS.md
- rules/agents.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- examples/CLAUDE.mdCLAUDE.md
- .cursor/rules/common-agents.mdCursor rule
- .cursor/rules/common-coding-style.mdCursor rule
- .cursor/rules/common-development-workflow.mdCursor rule
- .cursor/rules/common-git-workflow.mdCursor rule
- .cursor/rules/common-hooks.mdCursor rule
- .cursor/rules/common-patterns.mdCursor rule
- .cursor/rules/common-performance.mdCursor rule
- .cursor/rules/common-security.mdCursor rule
- .cursor/rules/common-testing.mdCursor rule
- .cursor/rules/golang-coding-style.mdCursor rule
- .cursor/rules/golang-hooks.mdCursor rule
- .cursor/rules/golang-patterns.mdCursor rule
- .cursor/rules/golang-security.mdCursor rule
- .cursor/rules/golang-testing.mdCursor rule
- .cursor/rules/python-coding-style.mdCursor rule
- .cursor/rules/python-hooks.mdCursor rule
- .cursor/rules/python-patterns.mdCursor rule
- .cursor/rules/python-security.mdCursor rule
- .cursor/rules/python-testing.mdCursor rule
- .cursor/rules/swift-coding-style.mdCursor rule
- .cursor/rules/swift-hooks.mdCursor rule
- .cursor/rules/swift-patterns.mdCursor rule
- .cursor/rules/swift-security.mdCursor rule
- .cursor/rules/swift-testing.mdCursor rule
- .cursor/rules/typescript-coding-style.mdCursor rule
- .cursor/rules/typescript-hooks.mdCursor rule
- .cursor/rules/typescript-patterns.mdCursor rule
- .cursor/rules/typescript-security.mdCursor rule
- .cursor/rules/typescript-testing.mdCursor rule
- api-designSkill
- article-writingSkill
- backend-patternsSkill
- coding-standardsSkill
- content-engineSkill
- e2e-testingSkill
- eval-harnessSkill
- frontend-patternsSkill
- frontend-slidesSkill
- investor-materialsSkill
- investor-outreachSkill
- market-researchSkill
- security-reviewSkill
- strategic-compactSkill
- tdd-workflowSkill
- verification-loopSkill
- oneskillSkill
- article-writingSkill
- content-engineSkill
- frontend-slidesSkill
- investor-materialsSkill
- investor-outreachSkill
- market-researchSkill
- api-designSkill
- article-writingSkill
- autonomous-loopsSkill
- The first 60 shown.
The file
Files
基于 Swift 协议的依赖注入(Testing)
通过将外部依赖(文件系统、网络、iCloud)抽象到精简且功能集中的协议(Protocols)后面,使 Swift 代码变得可测试。这种模式支持无需实际 I/O 即可进行确定性测试(Deterministic Tests)。
何时激活
- 编写访问文件系统、网络或外部 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. 创建用于测试的模拟实现(Mock)
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. 使用默认参数注入依赖
生产代码使用默认值;测试则注入模拟对象(Mocks)。
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 测试框架编写测试
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()
}
}最佳实践
- 单一职责(Single Responsibility):每个协议应仅处理一个关注点 —— 不要创建拥有过多方法的“万能协议(God Protocols)”。
- 符合 Sendable 协议:当协议在 Actor 边界之间使用时,此项为必须。
- 默认参数(Default Parameters):允许生产环境代码默认使用真实实现;仅在测试中才需要指定模拟对象(Mocks)。
- 错误模拟(Error Simulation):为模拟对象设计可配置的错误属性,以便测试失败路径。
- 仅对边界进行模拟:模拟外部依赖(文件系统、网络、API),不要对内部类型进行模拟。
需避免的反模式(Anti-Patterns)
- 创建一个涵盖所有外部访问的大而全的协议。
- 对没有外部依赖的内部类型进行模拟。
- 使用
#if DEBUG条件编译块而不是正确的依赖注入。 - 在与 Actor 配合使用时忘记让协议符合
Sendable。 - 过度工程(Over-engineering):如果一个类型没有外部依赖,则不需要为其定义协议。
何时使用
- 任何涉及文件系统、网络或外部 API 的 Swift 代码。
- 测试在真实环境下难以触发的错误处理路径。
- 构建需要同时在 App、测试和 SwiftUI 预览上下文中运行的模块。
- 使用 Swift 并发(Actor、结构化并发)并需要可测试架构的应用。
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

